pdo lastInsertId()一直返回0

时间:2013-04-07 22:28:21

标签: php mysql phpmyadmin

我有两个查询将数据插入到各自的表中。这很好。我一直尝试做的是在执行每个查询后获取lastInsertId并将这些值插入第三个表。但是,当我检查数据库时,输入值0。两个表都有一个自动递增的字段。你能告诉我的代码为什么会发生这种情况或有任何建议吗?我对php比较新,所以如果你注意到我编码的方式不整洁,特别是在我执行查询的最后,请告诉我。我很感激。

if ($oneWay)
    {
        $query = "INSERT INTO journey
        (from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
        VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')";
        $userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
    }
    else
    {
        $query = "INSERT INTO journey
        (from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
        VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')";
        //$userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
    }
    $queryfb = "INSERT INTO user
        (facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
        VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')";
        //$journeyID = "SELECT journey_id FROM `journey` ORDER BY journey_id DESC LIMIT 1";

    $queryUserJourney = "INSERT INTO user_journey
                        (user_id,journey_id)
                        VALUES('$lastUserID','$lastJourneyID')";

    $db->exec($query);
    $lastUserID = $db->lastInsertId();
    $db->exec($queryfb);
    $lastJourneyID = $db->lastInsertId();
    $db->exec($queryUserJourney);//problem: 0 values being entered???
}

更新

$db->exec($query);
    $lastUserID = $db->lastInsertId();
    $db->exec($queryfb);
    $lastJourneyID = $db->lastInsertId();
    $queryUserJourney = "INSERT INTO user_journey
                        (user_id,journey_id)
                        VALUES('$lastUserID','$lastJourneyID')";
    $db->exec($queryUserJourney);working thanks to jmadsen

3 个答案:

答案 0 :(得分:1)

您可能想尝试

$db->lastInsertId();

......相反。请注意d中的小写lastInsertId

Reference doc

答案 1 :(得分:1)

现在我喝咖啡了 - 在填充变量之前,你正在创建最后一个插入语句。我认为这是Maerlyn所暗示的

您需要将$ queryUserJourney移动到2个插入下方。

答案 2 :(得分:0)

@Colin,

PDO的最后一个插入ID返回一个自动增量主键的值,如果我没有完全弄错的话。它看起来像$ query的表没有这个