Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO - get current inserted ID

Tags:

php

pdo

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

like image 261
Tony Evyght Avatar asked Jun 01 '12 10:06

Tony Evyght


1 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();
like image 69
Khurram Avatar answered Sep 29 '22 15:09

Khurram