简体   繁体   中英

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!

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

PHP has a function called mysql_insert_id which will give you the same result as the query SELECT LAST_INSERT_ID(); .

mysql_insert_id is deprecated. So I think this thread needs to be updated.

mysql_insert_id is marked as deprecated since PHP 5.5.0.

In this example uid is the primary key of the table videos.

$row = DB::getMultipleRows("SELECT uid FROM videos WHERE uid=LAST_INSERT_ID();");
if (
    isset($row) &&
    is_array($row) &&
    isset($row['0']) &&
    is_array($row['0']) &&
    isset($row['0']['uid'])
) {
    $videoId = $row['0']['uid'];
}

There are dedicated functions for this - you shouldn't be using the SQL version as it doesn't work.

In the MySQL library you should use the mysql_insert_id function, whereas the mysqli object has an insert-id property. This of course may already be exposed in whatever DB class you're using.

You can try with PHP's mysql_insert_id function.

I think what's happening is that each DB::query call is in a different transaction, hence, $row is being empty. Maybe you can read DB:query documentation to try running both calls within the same transaction.

you should return lastInsertId of PDO to outer of your class . example:

class DB
{
    public $last_insert_id;
    function x()
    {
        $stmt = $db->prepare($Query);
        $stmt->execute();
        $this->last_insert_id = $db->lastInsertId();
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM