Sam Khan
Sam Khan

Reputation: 2477

Preventing ID duplication

I am using this below. Will it prevent ID duplication?

Code:

$new_generating_id = on the process page this will be generating a new id for each time the process page is being processed;

  $sql = "select `Message_id` from `queries_sent` 
  where message_id='$new_generating_id'";
  $query = mysql_query($sql) or die ("Error: ".mysql_error());

  while ($row = mysql_fetch_array($query)){

$storedid = $row['Message_id'];


  }
  mysql_free_result($query);

  if ( $new_generating_id == $storedid ) {
echo("An error occured.");
    die('');
   } else {
echo('');
   }

To play around with it to see if it works, I tested it by using known variables.

I changed $new_generating_id to an id that exists and when the db pulled it it gave the error message. What do you guys think?

Upvotes: 0

Views: 150

Answers (2)

geeky_bat
geeky_bat

Reputation: 318

Try using a timestamp value for identification. It's unique for each transaction submitted. the simplest form is:

$id='myid'.time();

Here I've used the string myid and concatenated it with the timestamp value (from the time() function). Now store this value in the database and perform operations on it.

Upvotes: 1

yaser
yaser

Reputation: 120

if you want to insert some unique string into the Message_id field, first mark the Message_id as unique in the table. then you can use something like this code to insert new ids into that table:

do {
    $uniqueId = md5(uniqid(mt_rand(), true));
    mysql_query("INSERT INTO queries_sent (Message_id) VALUES ('$uniqueId')");
} while (mysql_errno() == 1062);

Upvotes: 0

Related Questions