简体   繁体   English

PHP-MySQL INSERT查询不适用于表单操作

[英]PHP - MySQL INSERT query doesn't work with form action

I have a form that takes input from the user and stores it in a MySQL database when the user submits the form. 我有一个表单,可以从用户那里获取输入,并在用户提交表单时将其存储在MySQL数据库中。

print_r('<form action="" method="post">');
  /*
    form data, input tags, etc
  */
if (isset($_POST['Submit']))
{
    $sql = "INSERT INTO table
            VALUES (...)";
    $insert_form = $conn->query($sql);
}
print_r('</form>');

Initially, the user stayed on the page when they submitted the form and everything worked fine. 最初,用户在提交表单时停留在页面上,并且一切正常。 However, I updated the site to take the user to a new page after the form is submitted. 但是,我更新了站点,以便在提交表单后将用户带到新页面。 The first line of the above code now looks like this: 上面的代码的第一行现在看起来像这样:

print_r('<form action="next-page.php" method="post">');

I didn't think it was a significant change, but now whenever I try to Submit the form, I am taken to the next page without an insert into the database. 我不认为这是一个重大更改,但是现在每当我尝试提交表单时,都将直接进入下一页,而无需插入数据库。 When I remove the form action, the insert command works, and when I put it back in, it does not. 当我删除表单动作时,insert命令起作用,而当我将其放回时,则无效。

Any idea why this problem is occurring? 知道为什么会出现此问题吗?


I have found a workaround using the php header function: 我发现了使用php标头功能的解决方法:

if ($insert_form)
    header('Location: next-page.php');

..but it feels a little sloppy. ..但感觉有点草率。 Any comments on this? 对此有何评论?

You can remove the if statement; 您可以删除if语句; Insert next line after the $insert_form. 在$ insert_form之后插入下一行。

$sql = "INSERT INTO table
            VALUES (...)";
    $insert_form = $conn->query($sql);

    header("location: next-page.php");

print_r is mostly used to print out an array .If you wanna write your html inside a php echo will do your job easily.Normally a form submits the data to the current page if there isn't set or no action .If there is action it will take the form value to that next php file which you have set on your action and doesn't process anything within your current page. print_r主要是用来打印出array 。如果你想要写一个PHP中的HTML echo会做你的工作easily.Normally一个表单提交数据到当前页面,如果没有设置或没有action 。如果有action它会将表单value带到您在action设置的下一个php文件,并且不会在当前页面中处理任何内容。

echo'<form action="" method="post">';

/*
  form data, input tags, etc
*/
echo'</form>';

if (isset($_POST['Submit']))
 {
  $sql = "INSERT INTO table
        VALUES (...)";
  $insert_form = $conn->query($sql);
          header("location: next.php");

 } 

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

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