4


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!

3
  • A bit confused, are you trying to see if the record exists than don't run the insert command, or do you want to prevent duplicate entries by using keys and other constraints in mysql? Commented Mar 21, 2011 at 13:46
  • Better use the UNIQUE constraint to forbid duplicate values: “A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.” Commented Mar 21, 2011 at 13:46
  • No I just want a check, if it already exists it gives a warning, the user CAN ignore it, but can also cancel it. Commented Mar 21, 2011 at 13:47

5 Answers 5

7
$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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! It's that simple, huh. If I understand correctly, it checks if the $result is true/not-null, right?
Actually it checks the number of rows inside $result. If it's other than zero then you have a duplicate.
I use: if ($result) instead of the num_rows to check if $result is true, is that save?
$result returns the resource, which can also be an empty set (and that would be true)
4

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
         }
     }

1 Comment

Welcome to SO, thaks for posting. ;)
2

read about ON DUPLICATE KEY UPDATE

Comments

1

Another option is to use a SELECT COUNT() query which will tell you the number of duplications instead of just checking for any rows returned.

SELECT COUNT(*) FROM table WHERE field = '$field'

If you use the num rows method, it will be more efficient if you don't select all fields when you aren't going to use them - don't make the MySQL engine work harder than it needs to.

Comments

0

I realize this is an OLD post, but i had errors with the selected answer, as it would always return true when it was false, copied exactly from the answer above, so i wrote a slight variation of it.

function checkValid($ipCheck){
    $con=mysqli_connect("localhost","******","******","$DB_NAME");

    $result = mysqli_query($con,"SELECT * FROM $TBL_NAME");
    $end = true;
    while($row = mysqli_fetch_array($result) && $end)
    {
        if(strcmp($row['IP'],$ipCheck) == 0)
            $end = false;
    }   
    return $end; 
}

What this does, is it scans all until it reaches a false statement. If it doesn't, then it will remain true, meaning no duplicates, and move on, otherwise, it finds a duplicate and returns false, and triggers the counter statement.

So Assume i am trying to compare IP's from my database, and the column is IP:

if (!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
    $ip=$_SERVER['REMOTE_ADDR'];
}
if(checkValid($ip)){
    $sql = "INSERT INTO $TBL_NAME (IP) VALUES ('$ip')";
    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
}
else
    echo "IP Already Exists In Database";

I am extremely new to PHP, but this works just fine for my purposes, and it doesn't seem to affect my speed when loading the page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.