1

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);
?>
13
  • 2
    sounds like you have a loop somewhere in your php code... Commented Sep 11, 2013 at 16:04
  • 1
    Show the code above the $query Commented Sep 11, 2013 at 16:17
  • 1
    Please provide more code. The problem is not of insert code. In other code it is calling insert query more than once. Commented Sep 11, 2013 at 16:26
  • 1
    @ChrisPetrus Code seems perfect! When you open the page in browser it add record twice? Commented Sep 12, 2013 at 5:40
  • 1
    @ChrisPetrus Is your problem persist? Can you tell me which browser you are using? Commented Sep 12, 2013 at 9:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.