Monday, December 25, 2006

Mysql last inserted id

In a few articles on mysql the function LAST_INSERT_ID() is used to extract the last inserted id but i experienced a problem with it. When i insert multiple rows in one query the LAST_INSERT_ID displays the first inserted id and not the last.

INSERT INTO table (field1,field2) VALUES (value1,value2),(value3,value4)

The function is also restricted to the table field that has an AUTO_INCREMENT value. To avoid the problem and make it more flexible i created a maxFieldOfTable function.

function maxFieldOfTable($table,$field = 'id'){
$result = mysql_query('SELECT MAX('.$field.') FROM '.$table);
return (!$result)? mysql_error():mysql_result($result,0);
}

No comments: