-1

I am begineer in php . as this code i have been practising from tutorialspoint.com. in the site this code has produced the actual result but while running in my localhost it says undefined index : name in C:\xampp\htdocs\php\second.php on line 2.

<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<!------------Form----------------->
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
Krishna Dhakal
  • 1
  • 1
  • 1
  • 3

2 Answers2

0

use isset function to avoid undefined index error

Use

if( isset($_POST["name"]) || isset($_POST["age"])) 

instead of

if( $_POST["name"] || $_POST["age"] )
Md. Sahadat Hossain
  • 3,210
  • 4
  • 32
  • 55
  • Thank you Md. Sahadat Hossain. Why does that problem appears ? what is the differences in putting if( isset($_POST["name"]) || isset($_POST["age"])) and if( $_POST["name"] || $_POST["age"] ) , as this code have to be seem working in tutorials point.com why is it so .? – Krishna Dhakal May 18 '16 at 06:41
  • by using `isset` function you check the key is exists or not in the array – Md. Sahadat Hossain May 18 '16 at 06:43
0

Hello you have written html and php both in same page so first when you load page at that time you will not get any value in $_POST so you can try like below code then you will not get error.

<?php
if(isset($_POST))
{
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
}
?>
<!------------Form----------------->
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>

in this when first without submit page load it checks if $_POST isset then run php code otherwise not. actually php script run line by line so without $_POST if you are try to access then you will get error try this code may it helps you.

Denis Bhojvani
  • 817
  • 1
  • 9
  • 18