How to not clear input fields in php form?

2019-08-23 11:04发布

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

标签: php html sql input
7条回答
三岁会撩人
2楼-- · 2019-08-23 11:24

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.

查看更多
Root(大扎)
3楼-- · 2019-08-23 11:25

This has always worked for me:

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

查看更多
趁早两清
4楼-- · 2019-08-23 11:27

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.

查看更多
乱世女痞
5楼-- · 2019-08-23 11:29

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>
查看更多
等我变得足够好
6楼-- · 2019-08-23 11:29

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;
      }
查看更多
Evening l夕情丶
7楼-- · 2019-08-23 11:32

Simplest answer

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

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

查看更多
登录 后发表回答