简体   繁体   中英

Getting an ID for the last inserted value

I am trying to get the unique ID for the most recently added value to the database. I tried using LastInsertID bu I believe this is not compatible with MySQL (http://www.php.net/manual/en/pdo.lastinsertid.php).

$sql = "INSERT INTO discussion_links (link_url, link_title, link_source, publish_date, link_side, img_link) VALUES (?, ?, ?, ?, ?, ?)";
$sth=$db->prepare($sql);
$sth->execute(array($_POST['OP_link_url'], $_POST['OP_title'], $_POST['OP_source'], $_POST['OP_pub_date'], $_POST['OP_disc_side'], $_POST['OP_img_url']));
$op_link_id = $sth->$db->lastInsertID();

Here I get the error: PHP Catchable fatal error: Object of class PDO could not be converted to string

I also tried doing that last line as:

$op_link_id = $sth->fetch(PDO::lastInsertID);

And

$temp = $sth->fetch(PDO::FETCH_ASSOC);
$temp_op_link_id = $temp['link_id'];

But neither one worked (got some SQLState General Error 2053).

Thanks,

lastInsertID() should be called on PDO instance.

$op_link_id = $sth->$db->lastInsertID();

Should be

$op_link_id = $db->lastInsertID();

尝试这个

$op_link_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