簡體   English   中英

獲取最后插入值的ID

[英]Getting an ID for the last inserted value

我正在嘗試獲取數據庫最近添加的值的唯一ID。 我嘗試使用LastInsertID,但我認為這與MySQL(http://www.php.net/manual/zh/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();

在這里,我得到了錯誤:PHP可捕獲的致命錯誤:PDO類的對象無法轉換為字符串

我還嘗試將最后一行作為:

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

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

但是,沒有一個有效(得到了一些SQLState General Error 2053)。

謝謝,

應該在PDO實例上調用lastInsertID()

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

應該

$op_link_id = $db->lastInsertID();

嘗試這個

$op_link_id = $db->lastInsertID();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM