How to solve a Notice: Undefined index?

SS

Starting in PHP and following a tutorial I used the above code and ended up getting this error:

Notice: Undefined index: submit in C:\wamp\www\mezzo-com\reservas.php on line 3

How to solve it?

 16
Author: Maniero, 2014-06-18

3 answers

How is the form that calls C:\wamp\www\mezzo-com\reservas.php?

It needs to have a button being posted that sends information to the script PHP. It should have something like:

<input type="submit" value="Submit" name="submit">

It is actually possible that you have problems with other fields (name, mail, age, people, etc.) Without knowing the page that calls the script it becomes complicated to give more accurate information. But it is possible that you are even submitting a form and calling the script PHP straight. Or is calling but sending with GET instead of POST. There must be something like:

<form action="reservas.php" method="post">

But if you are calling the script in a context where this data is not available, then you need to make access to the element not happen by swapping your if in line 3 to:

if (isset($_POST["submit"])) {

This way you check the existence of the variable and its index without trying to access its value, not least because its value is not important but its existence. You will be checking if the operation can be done before letting the failure occur.

 23
Author: Maniero, 2014-11-27 10:54:59

This error indicates that there is no value in your variable $_POST with the name "submit". Either your form did not include this field, or the request is not a POST (I'm not sure about this second possibility as I have no practical experience with PHP).

Check the form that calls this URL. But if you want to make your code more robust, you can check if the key exists before using it, through the function array_key_exists or isset (the second also checks if the value is null):

if (array_key_exists("submit", $_POST)){    // Entra se "submit" existe

if (isset($_POST["submit"])){               // Entra se "submit" existe e não é null
 14
Author: mgibsonbr, 2014-06-18 23:50:26

The problem is the lack of the submit field in your form.

Make sure the form method is as POST, otherwise html by default will use GET.

 1
Author: Gustavo Gallas, 2016-06-15 13:02:44