我有this exact same issue ,但这个答案是旧的,我读过其他地方使用 mysql_insert_id() 是贬值的,应该避免在新代码中使用。
数据库是 InnoDB,这张表的主键设置为 auto_increment。
谁能看出我在这里做错了什么?我应该指出,我是一个初学者并且正在自学,所以我很抱歉这是显而易见的。
$query = "INSERT INTO VENUES (province,city,venue)" . "VALUES " . "('$province','$city','$venue')";
$result = $db->query($query);
if ($result) {
echo "$result row(s) sucessfully inserted.<br/>";
} else {
echo "$db->error<br/>";
}
$result = $db->query("select last_insert_id()");
echo $result->num_rows //returns 1
echo $result; //nothing beyond this line happens
更新:我正在使用 mysqli。
最佳答案
在使用 mysql_*
时,获取最后插入的 ID 的正确方法是调用 mysql_insert_id()
.
您正在阅读的内容部分正确 - mysql_insert_id
正在被弃用,但不仅仅是那个函数。所有 mysql_*
函数都被弃用了。 您应该使用 PDO 或 mysqli_*
。
在您的代码片段中,不清楚您使用的是哪个数据库访问库。由于您的调用似乎绑定(bind)到一个对象,很可能您正在使用 PDO 或 mysqli。
对于 PDO,您可以使用 PDO::lastInsertId
.
对于 mysqli
,使用 mysqli->insert_id
.
关于php - 使用 select last_insert_id() from php 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18607209/