开发者

PHP MySQL Check for duplicate entry?

开发者 https://www.devze.com 2023-02-17 23:06 出处:网络
How can I check if there already is a duplicate ent开发者_Python百科ry 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

How can I check if there already is a duplicate ent开发者_Python百科ry 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
         }
     }


read about ON DUPLICATE KEY UPDATE


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消