【问题标题】:php mysql avoid multiple/duplicate insertions from a single insert queryphp mysql避免来自单个插入查询的多次/重复插入
【发布时间】:2013-09-12 01:58:46
【问题描述】:

我正在尝试在示例表中插入一行。但是每次我运行网页时,都会插入多行。当我从 phpmyadmin 执行相同的查询时,我只插入了一行,这是正确的。我也尝试过 IGNORE 并设置主键。

以下是插入代码的sn-p:

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$dbname = "learnphp";
//connection open
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//testing for connection error
if(mysqli_connect_errno())
{
    die("Databse connection failed: ".mysqli_connect_error()."(".mysqli_connect_errno().")");
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Insert into Database with php</title>
</head>

<body>
<?php
$id = 1;
$name = 'sam';
$age  = 10;

$query = "INSERT INTO first (id,name,age) VALUES ('{id}','{$name}', '{$age}')";
$result = mysqli_query($connection,$query);
if($result)
{
    //Success
    //redirect_to("somepage.php");
    echo "Success".$result;
}
else
{
    //Failure
    //$message = "inserttion failed";
    die("Database query failed.".mysqli_error($connection));
}
?>
</body>
</html>
<?php
    //connection close
    mysqli_close($connection);
?>

【问题讨论】:

  • 听起来你的 php 代码中有一个循环......
  • 在$query上方显示代码
  • 请提供更多代码。问题不在于插入代码。在其他代码中,它不止一次调用插入查询。
  • @ChrisPetrus 代码看起来很完美!当您在浏览器中打开页面时,它会添加两次记录?
  • @ChrisPetrus 您的问题仍然存在吗?你能告诉我你用的是什么浏览器吗?

标签: php mysql


【解决方案1】:

您的代码似乎被执行了两次。我猜你的页面有某种刷新或标题更改。尝试放置一个出口;在 echo "Success" 之后,看看是否只插入了一行。我猜会是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    相关资源
    最近更新 更多