Getting The Last Auto Increment Field With PHP

On many occasions you need to find the value of the last auto increment field inserted into a MySQL table. For example within my Content Management System if someone creates a new web page and saves it the user is taken back to edit this new page. In order to do this I must retrieve the value of the last auto increment field inserted into the database.

To do this I use the php mysql_insert_id(); function.

You can add this value to a variable by using the following code:-

$MyValue = mysql_insert_id();

So with this variable you could select an item from a database eg:

$MyQuery = "SELECT * FROM MyTable WHERE UniqueField = $MyValue";

Of course you should always check that $MyValue is numeric for security so we don’t break the query. For this we could use the php intval function.

intval($MyValue);
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *