Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL Check for duplicate entry?

Tags:

php

mysql


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!

like image 209
Jay Wit Avatar asked Dec 10 '22 10:12

Jay Wit


2 Answers

$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);
}
like image 137
Saul Avatar answered Dec 19 '22 08:12

Saul


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
         }
     }
like image 30
John Avatar answered Dec 19 '22 09:12

John