Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last insert id

Tags:

php

mysql

I am inserting a record and i want to use the id of the last record inserted. This is what i have tried:

$sql = 'INSERT INTO customer
                (first_name, last_name, email, password, 
                date_created, dob, gender,  customer_type)
        VALUES(:first_name, :last_name, :email, :password, 
                :date_created, :dob, :gender, :customer_type)' 
        . ' SELECT LAST_INSERT_ID()' ;

I am getting the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()'.

Can anyone show me where is my mistake? Thanks!

like image 367
chupinette Avatar asked Feb 15 '10 14:02

chupinette


People also ask

How do I find the last insert ID in SQL?

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

How do I get the last insert ID from a specific table?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.

How do I get the last inserted row ID?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).


1 Answers

Check out mysql_insert_id()

mysql_query($sql);
$id = mysql_insert_id();

When that function is run after you've executed your INSERT statement in a mysql_query() command its result will be the ID of the row that was just created.

like image 105
nortron Avatar answered Oct 21 '22 19:10

nortron