我正在尝试获取数据库最近添加的值的唯一ID。我尝试使用LastInsertID bu我相信这是不兼容的MySQL(http://www.php.net/manual/en/pdo.lastinsertid.php)。获取最后插入的值的ID
$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一般错误2053)。
感谢,
$ ID = $这个 - > DB-> INSERT_ID();尝试这个? – dude
[如何获取最后插入的ID?]的可能的重复(http://stackoverflow.com/questions/7008656/how-to-get-the-last-inserted-id) – Hamish
@dude,感谢您的快速响应。我尝试在PHP代码中执行上述操作,并得到了服务器错误:PHP致命错误:在不在对象上下文中时使用$ this。我需要得到该ID才能在以后的另一个查询中使用它。 – Danconia