PHP MySQL Check for duplicates?


How to check if there is a duplicate record in the database? I do not want to prevent this, just a warning. So if it already exists, it just gives a warning, it is up to the user to ignore it or not.
Thanks in advance!

+3
source share
5 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);
}
+7
source

I made a friendlier way to handle duplicates for something like a user id. For example, if the user places the john identifier and that identifier already exists, it will automatically be changed to john1. If john1 exists, it will be automatically 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 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
         }
     }
+4
source
+2

- SELECT COUNT(), , .

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

num rows, , , , - MySQL- , .

0

, OLD-, , true, , , .

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

, , . , , , , false, .

, , IP , 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 it works great for my purposes, and it does not affect my speed when loading the page.

0
source

All Articles