简体   繁体   English

提交html数据并停留在同一页面上

[英]Submitting html data and staying on same page

I have a form page 我有一个表单页面

<html>
<body>
    <form action="insert.php" method="post">
        App Name: <input type="text" name="fname" /><br><br>
        App ID: <input type="text" name="lname" /><br><br>

        <input type="submit" name="SubmitButton"/>
    </form>
</body>
</html>

And this is the php page: 这是php页面:

<html>
<body>
<?php
    $con = mysql_connect("xxx","xxx","xxx");
    if (!$con)
    {
      die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("db", $con);         
    $sql="INSERT INTO app (fname, lname) VALUES('$_POST[fname]','$_POST[lname]')";

    if (!mysql_query($sql,$con))
    {
      die('Error: ' . mysql_error());
    }

    echo "1 record added";

    mysql_close($con)
?>
</body>
</html>

Now, I want it to display 1 record added on the same page as the form and not have the form send me to a new insert.php page with it. 现在,我希望它显示1 record added到与表单相同的页面上,而没有该表单将其发送到新的insert.php页面。 Basically, I want the submit form to stay in the same page with maybe aa new message popping up to show that it has worked. 基本上,我希望提交表单保留在同一页面上,也许会弹出一条新消息以表明它已经起作用。

I have already looked through some answers on stackoverflow like using 我已经看过关于stackoverflow的一些答案,例如使用

if(isset($_POST['SubmitButton']))

but it doesn't work. 但这不起作用。 Maybe I placed it wrong or used it incorrectly but could someone help me figure it out? 也许我把它放错了或使用不正确,但是有人可以帮我弄清楚吗?

Just make it an action to itself, and set an if $_POST['submit'] to add the records, and you can have both in the same file. 只需对其执行一个操作,然后设置if $_POST['submit']即可添加记录,并且您可以将它们都放在同一个文件中。 If you wish to do so without refreshing the page, you'll need to use AJAX. 如果您希望这样做而不刷新页面,则需要使用AJAX。

<html>
<body>
<?php
if (isset($_POST['SubmitButton'])) {
    $con = mysql_connect("xxx","xxx","xxx");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("db", $con);

    $sql="INSERT INTO app (fname, lname)
    VALUES
    ('$_POST[fname]','$_POST[lname]')";

    if (!mysql_query($sql,$con)) {
        die('Error: ' . mysql_error());
    }
    echo "1 record added";

    mysql_close($con)
}
?>


<form action="" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>

<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>

Also, mysql_* is deprecated , so you should consider converting to PDO or MySQLi to avoid SQL injection! 另外, 不建议使用 mysql_* ,因此您应考虑转换为PDO或MySQLi以避免SQL注入!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM