0

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?

John Watson
  • 2,554
  • 1
  • 17
  • 13
Sam Khan
  • 2,417
  • 5
  • 18
  • 16
  • 9
    HAve you considered using an `auto_increment` field? – Pekka Nov 28 '11 at 17:53
  • 1
    MySQL has a `unique` and `auto_increment` property for keys that should be used as IDs. You shouldn't be doing this in PHP. – Blender Nov 28 '11 at 17:54
  • If you want integer values, consider auto increment field as Pekka says. If you just want a unique value, use PHP's inbuilt `uniqid()` function – Ayush Nov 28 '11 at 17:55
  • I would recommend some `auto_increment` as well. If you don't want to or can't do that, maybe you could use the `uniqid` PHP built-in: [uniqid](http://php.net/manual/function.uniqid.php) – miku Nov 28 '11 at 17:55
  • @pekka yes i have that thats for the field 'id' this is for another field called 'message_id' – Sam Khan Nov 28 '11 at 17:58
  • @marcus if a post id already exists it should stop the form from inserting in the db the contents – Sam Khan Nov 28 '11 at 17:58

2 Answers2

1

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.

William
  • 3,511
  • 27
  • 35
geeky_bat
  • 318
  • 1
  • 3
  • 15
  • How come time() is 'unique for each transaction submitted' ? Unless you are 100% sure you have no more than 1tps. – Mchl Nov 28 '11 at 19:21
0

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);
yaser
  • 120
  • 2
  • 9