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"?


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

$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" />

Something like this should work.

    $txt = "";
} else {
    $txt = $_POST['stackoverflow'];

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

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:

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

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


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

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.