php PHP中的未定义索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5676945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Undefined index in PHP
提问by newbie
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
Good day!
再会!
I am having the following error in my code:
我的代码中出现以下错误:
<?php
if (!$_POST['SUBMIT']){ //ERROR: Undefined index
?>
<H2>Add Employee</H2>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">SSN</td>
<td><input name="SSN" type="text" id="SSN"></td>
</tr>
<tr>
<td width="100"> </td>
<td><input name="SUBMIT" type="SUBMIT" id="ADD" value="ADD"></td>
</tr>
</table>
</form>
<?php
}
else {
//code here
}
?>
How can I remove the error above? Thank you.
我怎样才能消除上面的错误?谢谢你。
回答by halfdan
It should be a notice and not an error.
它应该是一个通知而不是一个错误。
To fix is you'll have to check whether $_POST['submit']
is set:
要解决的是,您必须检查是否$_POST['submit']
已设置:
if(!isset($_POST['submit'])) {
...
}
回答by Tanner Ottinger
It's where you test to see that is isn't there. It should be !isset($_POST['SUBMIT'])
. This is because the index, SUBMIT
, won't be set, thus won't have a value such as true to pass the if(...)
. isset()
checks to see if the index/variable is actually set.
这是您测试以查看不存在的地方。应该是!isset($_POST['SUBMIT'])
。这是因为索引 ,SUBMIT
不会被设置,因此不会有诸如 true 之类的值来传递if(...)
. isset()
检查是否实际设置了索引/变量。
Try this:
尝试这个:
<?php
if (!isset($_POST['SUBMIT'])){ //ERROR: Undefined index
?>
<H2>Add Employee</H2>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">SSN</td>
<td><input name="SSN" type="text" id="SSN"></td>
</tr>
<tr>
<td width="100"> </td>
<td><input name="SUBMIT" type="SUBMIT" id="ADD" value="ADD"></td>
</tr>
</table>
</form>
<?php
}
else {
//code here
}
?>
回答by Florian
<?php
if (!isset($_POST['SUBMIT'])){ //ERROR: Undefined index
?>
This tests, if the index is set
这将测试是否设置了索引
回答by Spudley
Options:
选项:
- Disable warning messages, by editing the setting in PHP.ini
- Add an
@
sign in front of the variable name, which will suppress the error on that particular line. - Change your code to use
isset($_POST['SUBMIT'])
before checking it further.
- 通过编辑 PHP.ini 中的设置禁用警告消息
@
在变量名前添加一个符号,这将抑制该特定行上的错误。isset($_POST['SUBMIT'])
在进一步检查之前更改要使用的代码。
Of these, the third option is definitely the best. You shouldn't assume that any variable supplied by the user will be set as you expect; you should always check that it's set at all, and also that it's set to the expected values. Otherwise you are liable to be open to hacking attacks.
其中,第三种选择绝对是最好的。您不应该假设用户提供的任何变量都会按照您的预期进行设置;您应该始终检查它是否已设置,以及是否已设置为预期值。否则,您很容易受到黑客攻击。