2012-06-02 64 views
0

我有这个的phpmyadmin和mysql PDO 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,和所有我得到的是一个0返回。 任何帮助将不胜感激 谢谢

+1

首先检查,如果执行成功。因为如果不是,那么0可能是正确的,对吗? – hakre

+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仍然有效。

+0

啊,非常感谢你,这将工作! –