Вопрос

I want to add a user to the database. Every user has an unique ID that is automatic created(A_I). If I add an user I want to get this ID. I'm trying to do this with "insert_id", but if I do this I get an error.

$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;

Can anyone tell me what I'm doing wrong?

Это было полезно?

Решение

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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top