Clive Portman: code

Get id of last MySQL insert

Access it immediately using:


I was wanting to use this to create a catalogue number. I had an Item ID set to auto-increment and wanted to prefix to it but you can’t do that with MYSQL. To get around it, I used the mysql_insert_id() to identify the Item ID, then take that and add it to the prefix before updating the entry, like so:

$prefix = CAT;
$id = str_pad(mysql_insert_id(), 5, “0″, STR_PAD_LEFT);
$catnum = “UPDATE products SET product_cat = ‘$prefix$id’ WHERE product_id = ‘$id’”;
echo $catnum; // prints CAT00056

Note the use of str_pad() to add some leading zeros.