I have a Registration Form, but there are a few problems. This is my first registration form. Where the data is needed for data collection needs.
But when someone registers, a lot of duplicate data is in PHPMyAdmin. I’ve tried various ways, but you know, I’m just a student. I want to prevent duplicate email data.
<?php
$link = mysqli_connect("localhost", "xxxx", "", "db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$nama = mysqli_real_escape_string($link, $_REQUEST['nama']);
$nohp = mysqli_real_escape_string($link, $_REQUEST['nohp']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$instagram = mysqli_real_escape_string($link, $_REQUEST['instagram']);
$sql = "INSERT INTO event (nama, nohp, email, instagram) VALUES ('$nama', '$nohp', '$email', '$instagram')";
if(mysqli_query($link, $sql)){
echo "<p class='text-center'>Pendaftaran Berhasil. Akan kembali ke halaman utama dalam 5 detik.<br/>
Atau klik <a href='index.php'>HOME</a></p>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
What code do I need to add in it, so that someone who has registered their email will not be able to register again?
Sorry for my bad english
4
Answers
Put a unique constraint on
email
field directly onto table column. This will save you from duplicates (either inserted by your software or in other ways).After that, you can check explictly via PHP script if the email is already there (but this will cost you an extra query and so is a no-go; moreover as Qirel correctly pointed out, this will expose you to potential concurrency issues) or try to insert and check insertion result (correct and safer way).
Add a unique constraint on the column you wish to be unique, then insert the data without any regard for duplication – MySQL will return an error if the value was duplicate, so all you need to do is catch the error.
First, make the field on that table a unique value (you can not have duplicate values on the table when doing this – if you have duplicate values in the
event
table, you must fix that first).Then we simply try to insert the data (using a prepared statement instead of escaping), and catch the error – and check for the error-code which belongs to unique constraint errors.
You can add a
UNIQUE
constraint to the email field. This will be done by running the following query:After that, when you want to insert a new row with an email that already exists in your table, you’ll get an error like this:
#1062 - Duplicate entry ...
You can catch that exception and react on it in your PHP code like this:
You can give emailID unique constraint, whenever the user submits form with a emailID that already exists in the table, MYSQL will throw an exception which you will need to catch and display the error message.
Reference :https://www.w3schools.com/php/php_exception.asp