Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LAST_INSERT_ID() via PHP?

When I execute the following in the MySQL console, it works fine:

INSERT INTO videos (embed_code) VALUES ('test code here');
SELECT LAST_INSERT_ID();

But, when I execute the above queries via PHP, the result is empty.

Under the data abstraction, I am using a database access class named DB. This is how I have tried the above queries via PHP:

$embedCode = htmlentities($_POST['embed_code']);

//Insert video in database **WORKS**
DB::query("INSERT INTO videos (embed_code) VALUES ('$embedCode');");

//Retrieve id **DOES NOT WORK**
$row = DB::getSingleRow("SELECT LAST_INSERT_ID();");
$videoId = $row[0];

It is not reliable for me to select the new id by the embed_code, as the embed_code could be repeated.

Thanks!

like image 345
Mike Moore Avatar asked Aug 06 '10 16:08

Mike Moore


1 Answers

Doesn't your database class contain a function to grab the last insert ID? Try mysql_insert_id() otherwise instead.

http://nl.php.net/mysql_insert_id

like image 156
Sebs Avatar answered Oct 07 '22 17:10

Sebs