PDO-获取当前插入的ID

问题描述 投票:6回答:3
$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 ???? ;

我该怎么做?

php pdo
3个回答
17
投票
$query = "INSERT INTO news VALUES (NULL, :param1 , :param2  )";
$stmt = $pdo->prepare($query);

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

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

所以您可以这样做以获得最后插入的ID

$last_id = $pdo->lastInsertId();

2
投票

使用:

$last_insert_id = $pdo->lastInsertId();

1
投票

您可以使用PDO::lastInsertId

$last_insert_id = $pdo->lastInsertId();
© www.soinside.com 2019 - 2024. All rights reserved.