开发者

Undefined index in PHP [duplicate]

This question already has answers here: Closed 10 years ago.

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">&nbsp;</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.


It should be a notice and not an error.

To fix is you'll have to check whether $_POST['submit'] is set:

if(!isset($_POST['submit'])) {
    ...
}


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.

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">&nbsp;</td>
        <td><input name="SUBMIT" type="SUBMIT" id="ADD" value="ADD"></td>
   </tr>
</table>
</form>
<?php
    }
    else {
    //code here
    }
?>


<?php
  if (!isset($_POST['SUBMIT'])){   //ERROR: Undefined index
?>

This tests, if the index is set


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜