user2886091
user2886091

Reputation: 725

php inserts duplicate records

I am new to php. I have downloaded xampp and created a database with 2 columns ID (primary key, auto-increment), CENA (INT values)

In my index.php I have just one input text and a submit button:

 <body>
     <form action="submit.php" method="post">
         <input type="text" name="cena"><label> cena</label>
         <input type="submit" value="Submit">
     </form>
 </body>

And this is my submit script:

$sql = "INSERT INTO updat (CENA) VALUES ('$_POST[cena]')";

mysqli_query($con, $sql);

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

echo "1 record added";
mysqli_close($con);

When I enter a value into text input, and hit the submit button it echos: "1 record added" But when I look into my databse in phpMyAdmin I see 2 records.

EXAMPLE:

I enter 123 into textinput

in phpMyAdmin I see:

+----+------+
| ID | CENA |
+----+------+
|  1 |  123 |
|  2 |  123 |
+----+------+

I am not using any loops so why 2 records?

Thank you

Upvotes: 1

Views: 2776

Answers (2)

Usman Khalid Qureshi
Usman Khalid Qureshi

Reputation: 146

Here you are using the INSERT statement 2 times.

mysqli_query($con,$sql); //Remove this line

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

Just remove one of them

Upvotes: -1

sergio
sergio

Reputation: 5260

It is becuse you use twice mysqli_query:

mysqli_query($con,$sql)

So, first when you insert data, and after when you checking in if() statement, so just delete first mysql_query, for example in that way :

$sql="INSERT INTO updat (CENA) VALUES ('$_POST[cena]')";
 if (!mysqli_query($con,$sql))
 {
 die('Error: ' . mysqli_error($con));
 }

Upvotes: 6

Related Questions