dq13733519262 2015-07-23 16:20 采纳率: 0%
浏览 69

提交HTML数据并保持在同一页面上

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:

<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. Basically, I want the submit form to stay in the same page with maybe a a new message popping up to show that it has worked.

I have already looked through some answers on stackoverflow like using

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?

  • 写回答

1条回答 默认 最新

  • duanbo7517 2015-07-23 16:23
    关注

    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 you wish to do so without refreshing the page, you'll need to use 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!

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题