0

Im writing this code in PHP and after i click Submit I want the values to be saved in the texbox. first time when I open the page I see some errors inside textfild?How can i fix this ?

<html>
<body>
<form action="" method="GET">
First number<input type="text" name="num1" placeholder="<?php echo $_GET['num1']  ; }?>"/>
Second number<input type="text" name="num2" placeholder="<?php echo $_GET['num2'] ; ?>"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if(isset($_POST['submit']))
{

$num1=$_GET['num1'];
$num1=$_GET['num2'];
$sum=($num1+$num2);
echo "Sum is :<input type='text' value='$sum'/>";   
}

?>
</body>
</html>
krisi
  • 3
  • 7

1 Answers1

0

When you first open the page, the GET variables are not yet set.

Do this instead:

First number<input type="text" name="num1" placeholder="<?php echo (isset($_GET['num1']))? $_GET['num1'] : ""; ?>"/>
Second number<input type="text" name="num2" placeholder="<?php echo (isset($_GET['num2']))? $_GET['num2'] : ""; ?>"/>

This will verify (using ternary expressions) if the get variable is set, if it is, then it will apply the value to the textbox.

Also, as mentioned below by mopo, this is a new feature in PHP7 that will also work, a simpler way.

First number<input type="text" name="num1" placeholder="<?php echo $_GET['num1'] ?? ""; ?>"/>
Second number<input type="text" name="num2" placeholder="<?php echo $_GET['num2'] ?? ""; ?>"/>

Also, you shouldn't check if the submit button is set using POST... it shouldn't work.

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

You can verify if both $_GET['num1'] and $_GET['num2'] are set instead.

Eckstein
  • 785
  • 9
  • 27
Phiter
  • 14,570
  • 14
  • 50
  • 84