insert-id

PHP query insert_id not working


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?


Solution

  • 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();