Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an identifier for a mysql row

Tags:

php

mysql

I am setting up an event in php, and saving it to mysql. Later, I want to update the event, but in order to know which event needs to be updated, I use the time it was created.

However if several events start at the exact same second I might run into problems down the line if we have many users. My solution is to check for starttime and usernumber, which I believe should be unique enough. Is this okay? is there a better way to do it?

First, when creating the event:

$starttime = time();
mysql_query("INSERT INTO events (userid, starttime) 
             VALUES ('$userid', '$starttime')");

Later, updating the event:

mysql_query("UPDATE events 
             SET newdata='$newdata' 
             WHERE starttime='$starttime' 
             AND userid='$userid'"); 
like image 408
Lucy Weatherford Avatar asked Nov 17 '25 06:11

Lucy Weatherford


1 Answers

Bad bad way to go. Just put an auto_incrementing primary key ID field on that table, which will give you a guaranteed unique non-repeat value you can UNIQUELY identify a row with without any fear of overlaps/conflicts:

ALTER TABLE events ADD id int unsigned primary key auto_increment;

You can retrieve that value automatically after an insert query:

   $sql = "INSERT ...";
   $result = mysql_query($sql) or die(mysql_error());
   $new_id = mysql_insert_id(); // see here: http://us2.php.net/manual/en/function.mysql-insert-id.php

   ... other stuff...

   $sql = "UPDATE ... WHERE id = $new_id;":
   $result = mysql_query($sql) or die(mysql_error());
like image 65
Marc B Avatar answered Nov 19 '25 22:11

Marc B