Wednesday, March 25, 2009

Notice: Undefined index: (php)

Notice: Undefined index:
Sometimes you get this notice (This is not a error). lets see a example why you get this notice or warning.


<?php

error_reporting(E_ALL);

echo $name= $_POST["name"];
echo $number= $_POST["number"];

?>

<html>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr>
<td>Name :</td>
<td> <input type="text" name="name" /></td>
</tr>
<tr>
<td>Tel: Number :</td>
<td> <input type="text" name="number" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="sub" value="Add" /></td>
</tr>
</table>
</form>
</body>
</html>



When you initially load this page you will get a notice like following.
Undefined index

This notice is shown because your php.ini file has enabled Notices to display or you may have a set error_reporting() function to E_ALL or to display notices.

The reason for the notice because when the page is load it search for the $_POST["name"] and $_POST["number"] which actually not available, $_POST indexes are set when you submit the form not when you just load the page.

Solutions:
1) you can fix the error reporting levels in php.ini or by error_reporting() function.

or

Change the code like this.


if(isset($_POST['sub']))
{
echo $name= $_POST["name"];
echo $number= $_POST["number"];
}


This will make the code run only when you submit the add button.

No comments:

Post a Comment