Home » Php » php – PDO – get current inserted ID

php – PDO – get current inserted ID

Posted by: admin July 12, 2020 Leave a comment

Questions:
$query = "INSERT INTO news VALUES (NULL, :param1 , :param2  )";
$stmt = $pdo->prepare($query);

$params = array(
    "param1" => $p['title'],
    "param2" => $p['body'],
);

$data = $stmt->execute($params);

// here i would like get current inserted ID. Is possible?

$id = $data->id ???? ;

How can i make this?

How to&Answers:
$query = "INSERT INTO news VALUES (NULL, :param1 , :param2  )";
$stmt = $pdo->prepare($query);

$params = array(
    "param1" => $p['title'],
    "param2" => $p['body'],
);

$data = $stmt->execute($params);

so you can do like this to get last inserted Id

$last_id = $pdo->lastInsertId();

Answer:

Use :

$last_insert_id = $pdo->lastInsertId();

Answer:

You could use PDO::lastInsertId

$last_insert_id = $pdo->lastInsertId();