简体   繁体   English

从PHP使用select last_insert_id()无法正常工作

[英]Using select last_insert_id() from php not working

I have this exact same issue , but that answer is old, and I've read other places the use of mysql_insert_id() is depreciated and should be avoided in new code. 我有完全相同的问题 ,但是答案很旧,并且我读过其他地方,mysql_insert_id()的使用已过时,应在新代码中避免使用。

The database is InnoDB and the primary key for this table is set to auto_increment. 数据库是InnoDB,此表的主键设置为auto_increment。

Can anyone see what I'm doing wrong here? 有人可以在这里看到我在做什么错吗? I should note I'm a beginner and learning on my own, so I apologize is this is glaringly obvious. 我应该注意,我是一个初学者,一个人学习,所以我很抱歉这是显而易见的。

$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

UPDATE: I am using mysqli. 更新:我正在使用mysqli。

The correct way to get the last inserted id, when using mysql_* is to make a call to mysql_insert_id() . 使用mysql_*时,获取最后插入的id的正确方法是调用mysql_insert_id()

What you are reading is partially correct - mysql_insert_id is in the process of being deprecated, but it's not just that function. 您正在阅读的内容部分正确mysql_insert_id正在弃用过程中,但不仅限于此功能。 All mysql_* functions are being deprecated. 不建议使用所有的mysql_*函数。 Instead you should use either PDO or mysqli_* . 相反,您应该使用PDO或mysqli_*

In your code snippet, it is unclear which database access library you are using. 在您的代码段中,不清楚您正在使用哪个数据库访问库。 Since your calls seem to be bound to an object, it is likely you are using PDO or mysqli. 由于您的调用似乎已绑定到对象,因此很可能正在使用PDO或mysqli。

For PDO you can use PDO::lastInsertId . 对于PDO,您可以使用PDO::lastInsertId
For mysqli , use mysqli->insert_id . 对于mysqli ,请使用mysqli->insert_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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