0

对你们来说一个简单的问题 - 我正在尝试将数据提交到数据库中的表并且它成功地完成了,然后继续向表中添加无限数量的空白行。

这是代码:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$about = $_POST['about'];
$msg  = $_POST['message'];

$con = mysql_connect("DATABASE","USERNAME","PASSWORD");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
$database = mysql_select_db("benpearl_co_uk_db", $con);
if(!$database) {
    die('Houston, we have a problem: ' . mysql_error());
}

    $sql="INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";

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

?>
    <script language="JavaScript">
    self.location="?email=1";
    </script>

重申一下,我在连接数据库或成功将表单中的值放入表中没有问题。但是,一旦输入了值,页面就会不断刷新,将空行添加到表中。

我的代码有什么问题?

4

4 回答 4

0

you should run the insert only when the button submit is clicked if you have , so even when you load the page again it will not insert again the data

try doing this

   if (isset($_POST['submit']))     //then run your insert sql
   {

    $sql="INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";

    if (!mysql_query($sql,$con))
     {
        die('Error: ' . mysql_error());
     }
     }
于 2012-12-18T11:25:16.400 回答
0

问题在这里:

<script language="JavaScript">
self.location="?email=1";
</script>

Self.location 重定向浏览器,您通过添加 url 参数重定向到同一页面,email = 1这当然会再次运行脚本导致无限循环。您应该检查是否$_POST包含有效值,然后才插入数据库。

于 2012-12-18T11:11:40.233 回答
0

好吧,这正是您的代码所做的:

  • 在服务器端写一个 DB 行
  • 将页面返回给客户端,其中包含<script language="JavaScript">self.location="?email=1";</script>
  • 这反过来又使页面刷新。

您需要使 JS 部分成为有条件的。

于 2012-12-18T11:12:07.410 回答
0

您始终使用以下命令重定向到同一页面:

self.location="?email=1";

尝试类似:

$sql = "INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";

if (mysql_query($sql, $con))
{
    header('Location: $other_page');
}

die('Error: ' . mysql_error());
于 2012-12-18T11:14:55.450 回答