-1

我想在数据库中添加一个用户。每个用户都有一个自动创建的唯一 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;

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

4

1 回答 1

3

You are using PDO not mysqli. You need to use PDO::lastInsertId(). Like this:

$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();
于 2014-02-19T18:50:23.743 回答