How to not clear input fields in php form?

2019-08-23 11:41发布

问题:

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

回答1:

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>


回答2:

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.



回答3:

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>


回答4:

This has always worked for me:

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



回答5:

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.



回答6:

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;
      }


回答7:

Simplest answer

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

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



标签: php html sql input