mysql_insert_id()

$query = “INSERT something into some table somewhere“;
//  Run query
$row = mysql_query($query);

// Make sure query inserted user successfully
if ( !mysql_insert_id() ){
echo($query);
die(“Error: User not added to database.”);
}

This little nifty function “mysql_insert_id()” has solved several of my problems, although the problems were never surfaced, I knew that it would lead to problems in high traffic scenarios. My old method was to do the insert and then immediately call for the latest ‘ID’ by date… the problem is what happens when two people click the ‘submit’ button at the same time? The ‘ID’ returned to the user may be the other persons! All depending on the somewhat random order that the code gets executed. I knew this would be a problem, but now after finding this nifty function, it has alleviated all of that!

http://php.net/manual/en/function.mysql-insert-id.php Says this:

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

For you PHP/MySQL programmers out there, note this down! It is good to know for the bigger than normal DB-based project.

Tid bits

Life is busy, summer is here… There is so much to do outside that it is tough staying inside and programming. I am waiting for the day where day-light laptop screens become common place. I would really enjoy that. So as to keep this blog with some timely updates I created a new category called “Tid Bits”. This new category will be little snippets of useful code that I find. I’m gonna add a Menu link to it, as to make navigation to it easier.