How can I check if there already is a duplicate entry in the database? I don't want to prevent it, just a warning. So if it already exists it simply gives a warning, it's up to the user to ignore it or not.
Thanks in advance!
$key_id = 123;
$result = mysql_query("SELECT * FROM table WHERE key_id='$key_id'");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
trigger_error('It exists.', E_USER_WARNING);
}
I made a friendlier way to handle duplicates for something like a user ID. For example, if a user puts in an id john and that ID already exists, it will automatically be changed to john1. If john1 exists it will automatically be changed to john2, etc.
// Force the while statement to execute once
$usercount = 1;
// The number to append to the duplicate value
$incrementcount = 0;
// Store the original value
$origuserid = $userid;
while ($usercount != 0) { // Query the database for the current ID
$query = "SELECT COUNT(*) FROM userlist WHERE userid = '$userid'";
if ($stmt = $con->prepare($query)) {
$stmt->execute();
$stmt->close();
$stmt->bind_result($usercount);
$stmt->fetch();
} else {
die('Query error');
}
if ($usercount != 0) {
// if count is anything other than zero, it's a duplicate entry
$incrementcount++; // value to append
$userid = $origuserid . $incrementcount; // append value to original user id
// the while loop will execute again and keep incrementing the value appended
// to the ID until the value is unique
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With