phpmyadmin和mysql pdo lastInsertId()

时间:2012-06-02 21:39:23

标签: php mysql pdo phpmyadmin lastinsertid

我有这个

$query = "INSERT INTO players VALUES (
                    UUID(),
                    :firstname,
                    :lastname,
                    :age,
                    :birthplace,
                    :height,
                    :weight,
                    :bats,
                    :throws,
                    :position,
                    :jersey,
                    :status,
                    :team,
                    :image_path
                )";
    $sth = $db->prepare($query);
    $sth->execute(array(
        ':firstname' => $firstname,
        ':lastname' => $lastname,
        ':age' => $age,
        ':birthplace' => $birthplace,
        ':height' => $height,
        ':weight' => $weight,
        ':bats' => $bats,
        ':throws' => $throws,
        ':position' => $position,
        ':jersey' => $jersey,
        ':status' => $status,
        ':team' => $team,
        ':image_path' => $image_path
    ));

    $id = $db->lastInsertId();
    return $id;

我正在尝试返回插入的最后一个ID,而我得到的所有ID都返回0。 任何帮助是极大的赞赏 感谢

1 个答案:

答案 0 :(得分:3)

LAST_INSERT_ID()和朋友只能使用通过AUTO_INCREMENT列创建的整数ID。您需要运行两个查询 - 第一个

SELECT UUID() AS newuuid;
然后

获取并存储此结果(例如在$uuid中),然后

"INSERT INTO players VALUES (
                    :uuid,
                    :firstname,
                    :lastname,
...
execute(array(
        ':uuid' => $uuid,
        ':firstname' => $firstname,
        ':lastname' => $lastname,
        ':age' => $age,

$uuid仍然有效。