Tipu K Tipu K - 1 year ago 39
PHP Question

how to stop duplicating rows being created in mysql

I am new to web development and it's my first code in MySQL (an exercise). My problem is that the code (despite being a copy of example answer provided in the exercise) is creating many problems. The recent is:

'it's duplicating the entries with the UPDATE command'. I have tried many solutions on the web and on this site but no success.

  1. There have been many other problems but google, this site and I were able to overcome them. Still there is one question remaining: first version with {} was not working , so I researched and tried alternative syntax in the beginning only and as you can see there is no : after else because the code is working only without :

3.I hope you understand and will help me. Thanks a galaxy in advance.

$link= mysqli_connect(""); //connection details omitted
if (array_key_exists("submit",$_POST)): // checks when submitted
$error=""; //variable for errors
if (!$_POST['email']){
$error .= "An email address is required<br>"; //if email not entered
if (!$_POST['password']){
$error .= "A password is required<br>"; //if password missing
//if ($error != "")
//$error = "<p>There were errors in your submission:</p>" . $error; //pre-text for errors joined with concatation
else //if I use { or : it doesn't work,
//variable for query select and run result
$check ="select id from users where email='".mysqli_real_escape_string($link, $_POST['email'])."'";
// print_r($check);
$result =mysqli_query($link, $check);
if (mysqli_num_rows($result)>0) //check if an id is found with the given email
$error="This email address has been taken."; //echoed error
$email= mysqli_real_escape_string($link, $_POST['email']);
$password=mysqli_real_escape_string($link, $_POST['password']);
$insert = "insert into users (email, password) values ('$email', '$password') ";
//print_r($insert);//insert query
$result=mysqli_query ($link,$insert);
if (!mysqli_query($link, $insert)){
$error= "There was a problem. Try again!"; //the connection failed message
$hash="update users set password='$md' where id=$id";
mysqli_query($link, $hash);
echo "Sign Up successful!"; //success message

Answer Source

You're making a call to mysqli_query twice so the INSERT query is executed twice.

Fix it like this:

$result=mysqli_query ($link,$insert);       
if (!$result){