phpmyadmin and mysql pdo lastInsertId()

827 Views Asked by At

i have this

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

and i'm trying to return the last ID that was inserted, and all i'm getting is a 0 returned. any help is greatly appreciated thanks

1

There are 1 best solutions below

0
On

LAST_INSERT_ID() and friends will work only for integer IDs that are created via an AUTO_INCREMENT column. You need to run two queries - first

SELECT UUID() AS newuuid;

then fetch and store this result (e.g. in $uuid), then

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

leaving you with the $uuid still valid.