I'm trying to make a script that 1) Checks if an entry with the given email address already exists in the DB, and if not 2) Populates the DB with a new entry.
This is the code I currently have:
$result = mysql_query("SELECT * FROM cbsclassy WHERE email = '$email' LIMIT 1");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) { echo "It seems that you're already participating. It is
only allowed to make one entry into the competition. <a href=index.html>Click to
return to the previous page</a>.";
}
else { $sql="INSERT INTO cbsclassy (name, email, answer) VALUES
('$name','$email','$answer')";
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error());
}
echo "You're now participating in the contest. The winners will be
notified directly via email. Good luck! <a href=index.html>Click
to return to the previous page</a>.";
}
The script is working fine when it comes to populating the DB, however it doesn't catch if the email address already exists in the DB. Can anyone spot the problem?
You have two }
's before the else so it gets triggered every time.
It'd be more efficient to set a UNIQUE KEY
on the email field and then check the amount of affected rows
when inserting to know if it existed or not.
Also as noted in the comments your code is vulnerable to SQL Injection
. I recommend you use prepared statements
.
Correct the if/else construct
if ($num_rows > 0) { echo "It seems that you're already participating. It is
only allowed to make one entry into the competition. <a href=index.html>Click to
return to the previous page</a>.";
} //here remove a }
else { $sql="INSERT INTO cbsclassy (name, email, answer) VALUES
('$name','$email','$answer')";
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error());
}
//and also here
echo "You're now participating in the contest. The winners will be
notified directly via email. Good luck! <a href=index.html>Click
to return to the previous page</a>.";
}