php mysql避免单个插入查询中的多个/重复插入

时间:2013-09-11 16:01:08

标签: php mysql

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

DB Table Structure that am using

以下是插入代码的片段:

<?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);
?>

1 个答案:

答案 0 :(得分:2)

似乎你的代码被执行了两次。我猜你的页面有某种刷新或标题已更改。尝试放置出口;在回显“成功”之后,看看是否只插入了一行。我猜这将是这样的。