How to not clear input fields in php form?

2013-05-03 php html sql input

I have a webpage that uses php and has a bunch of input fields in which a user enters some data and I turn the input into an SQL statement to query some database. I successfully parse the input fields and put the SQL statement together but when they click the "submit" button, all the input fields get cleared. How can I make it so these input fields don't get erase every time the user clicks "submit"?

Answers

You need to check if the POST values (assuming you're using POST) are already set when the page loads (because they have already been submitted). If they are set, echo their contents into the value attributes of the form fields, or set checked=checked etc. depending on the field types.

Have you used sessions and Cookies in PHP??

You can store the values in session on form submit before updating in Database for a user, then check if there is a session for user and value is set for field output the value else output null.

Store them in local variables like

<?php
$name = '';
$last = '';

if(isset($_POST['post_me'])) {
   $name = $_POST['post_me'];
   $last = $_POST['last'];
   //Process further
}
?>
<form method="post">
  <input type="text" name="name" value="<?php echo $name; ?>" />
  <input type="text" name="last" value="<?php echo $last; ?>" />
  <input type="submit" name="post_me" />
</form>

Something like this should work.

<?
if(!isset($_POST['stackoverflow'])){
    $txt = "";
} else {
    $txt = $_POST['stackoverflow'];
}  
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="" method="post">
        <input type="text" name="stackoverflow" value="<?= $txt ?>">
    </form>
</body>
</html>

This has always worked for me:

<input type="text" name="somename" value="<?php echo htmlspecialchars($_POST['somename']); ?>">

The key is to store the post values in session and display it using value tag. Example:
HTML:

    <form action="index.php" method="post">
        <input type="text" name="name" placeholder="First Name"
        value="<?php
        if (isset($_SESSION['name'])) {
            echo $_SESSION['name'];
        }?>" >

       <input type="submit" name="submit">
   </form>

PHP:

      session_start();
      if (isset($_POST['submit'])) {
        $name=$_POST['name']); 
        $_SESSION['name']=$name;
      }

Simplest answer

`<form method="post" onsubmit="return false">`

coding your input with PHP is dangerous even if with htmlentities - hope this helps

You just have to make sure the HTML input value has a php echo statement of the appropriate php variable for that field.

Related