【问题标题】:PHP query insert_id not workingPHP查询insert_id不起作用
【发布时间】:2014-03-20 07:42:22
【问题描述】:

我想在数据库中添加一个用户。每个用户都有一个自动创建的唯一 ID (A_I)。如果我添加一个用户,我想获得这个 ID。我正在尝试使用“insert_id”执行此操作,但如果执行此操作,我会收到错误消息。

$sth=Connection()->prepare ("INSERT INTO Users (Username, Password) VALUES(:Username, :Password)");
$sth->BindValue(":Username", $username, PDO::PARAM_STR);
$sth->BindValue(":Password", $password, PDO::PARAM_STR);
$sth->execute();
$ID = $sth->insert_id;

谁能告诉我我做错了什么?

【问题讨论】:

标签: insert-id


【解决方案1】:

您使用的是PDO 而不是mysqli。您需要使用PDO::lastInsertId()。像这样:

$con = Connection();
$sth= $con->prepare ("INSERT INTO Users (Username, Password) VALUES(:Username, :Password)");
$sth->BindValue(":Username", $username, PDO::PARAM_STR);
$sth->BindValue(":Password", $password, PDO::PARAM_STR);
$sth->execute();
$ID = $con->lastInsertId();

【讨论】:

  • 感谢您的快速响应。如果我这样做,它仍然会出现错误:致命错误:调用未定义的方法 PDOStatement::lastInsertId()
猜你喜欢
  • 1970-01-01
  • 2016-08-10
  • 2014-12-09
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
相关资源
最近更新 更多