Chris Petrus
Chris Petrus

Reputation: 203

php mysql avoid multiple/duplicate insertions from a single insert query

I am trying to insert one row into a sample table. But every time I run the webpage, multiple rows are getting inserted. When I execute the same query from phpmyadmin, I get only one row inserted, which is right. I've also tried IGNORE and setting a primary key.

DB Table Structure that am using

The following is a snippet of the insert code:

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

Upvotes: 1

Views: 2108

Answers (1)

Thornuko
Thornuko

Reputation: 287

It seems your code is getting executed twice. I am guessing your page has some sort of refresh or header changed. Try placing an exit; after the echo "Success" and see if only one row is inserted. I am guessing that will be the case.

Upvotes: 2

Related Questions