Undefined index errors accessing $_POST

2019-07-18 03:10发布

问题:

I keep trying to fix this but it's giving me the same errors:

Notice: Undefined index: items in C:\xampp\htdocs\shop.php on line 9

Notice: Undefined index: body in C:\xampp\htdocs\shop.php on line 24

Here is my code:

<form action="" method="post">
    <input type="radio" name="items" value="fed" /> Fed<br />
    <input type="radio" name="items" value="body" /> Body<Br>
    <input type="submit" name="submit"><br>
</form> 

<?php
if(isset($_POST['submit'])) {
     $items = $_POST['items'];
     if($items=="fed") {
         echo "You choose feds";    
         die();
     }
     else
         echo "<Form action='' method='POST'>
         <select name='body'>
         <option value='head'>Head</option>
         </select>
         <input type='submit' name='submit' value='submit' /><br />
         </form>";

 if(isset($_POST['submit'])) {
    $body = $_POST['body'];
    $connect = mysql_connect("localhost","root","")or die(mysql_error());
    mysql_select_db("feds",$connect)or die(mysql_error());

    $merchandise = mysql_query("SELECT * FROM merchandise WHERE body_part='$body' ")or     die(mysql_error());

    while($row = mysql_fetch_array($merchandise)) {
        echo $row['item'];  
        echo "<bR>";
    }
}


} 
?>

回答1:

The error messages say that you're accessing an item of an array that doesn't exist!

But in general you should check the existence of these variables (even if you're sure that the form was sent):

$items = isset($_POST['items']) ? $_POST['items'] : outputError('...');

And please fix your SQL injection security hole!!

$body = mysql_real_escape_string( $_POST['body'] );

Please consider upgrading to MySQLi or PDO, too! There are many good resources on these topics out there.



回答2:

These are not errors, they are notices. But they should be fixed in the production environment, as this gives you a hint that your code may not be working correctly in some cases.

Solution

Depending on what exactly you want to achieve, you can use the following code:

$items = array_key_exists('items', $_POST) ? $_POST['items'] : '';

and you are sure your $items variable contains something (at least empty string). Of course depending on your code architecture, you can replace empty string with false or null, but it is up to you.

Tip about using isset() or empty()

Do not use them for checking if the specific element exists in array - use array_key_exists(). What is the difference?

Let's assume $my_array looks like that:

$my_array = array(
    'a' => 'abc',
    'b' => 0,
    'c' => '',
    'd' => null,
);

then:

  • empty() on $my_array['b'], $my_array['c'] and $my_array['d'] will return true, as all these values are considered empty, and on $my_array['e'] will also return true, as non-existent value/variable is also considered empty,
  • isset() on all elements will return true with exception of $my_array['d'], because isset() treats variables equal to null as not set. isset($my_array['e']) will also return `false (because variable is not set),
  • array_key_exists() will return true for every key that actually exists within array, and will return false if it does not,

So, as mentioned above, the better option for checking whether some element is defined in array is to use array_key_exists(), as it does not skip "empty" or null values.

Appendix

There are links to the documentation:

  • isset() - determines if a variable is set and is not NULL,
  • empty() - determines whether a variable is empty (empty string, 0 as integer, 0.0 as float, '0' - zero as string, null, false or empty array array()),
  • array_key_exists() - actually checks if the given key or index exists in the array,


回答3:

You should make a hidden input for each form, instead af trying to listen to a submit button.. not all versions of php register the submit button as a value. Also you wrote the "if(isset($_POST['submit']))" twice, which will make php return both if-statements true.. hope this helps



回答4:

I am not able to understand the logic as to what you are trying to do. Can you explain a bit more? Also your first if condition is closed incorrectly. Your structure is as follows:

if(user submits) //true
{
if(){ do something}
else{ do something}

if(user submits) //true
{
//you call body variable, which is not defined the first time user submits the page, thus the error
}

}//original if ends

So, check the brackets.



回答5:

Try changing the code that echoes your form out to this:-

echo "<Form action='' method='POST'>
     <select name='body' id='body'>
     <option value='head'>Head</option>
     </select>
     <input type='submit' id='submit' name='submit' value='submit' /><br />
     </form>";

Notice I have added id's to the form elements, it is best to use both id and name attributes set to the same value for forms.



回答6:

Undefined index means that you are trying to access an array key that does not exist. Your form probably is not posting like you are expecting. A simple:

print_r($_POST);

will show you what is posting.



回答7:

Hey just use method as "POST" instead of "post" .hope so it would solve your problem just like mine.

Happy coding



标签: php html forms