1

我有两个查询将数据插入到各自的表中。这很好用。我一直在尝试做的是在执行每个查询后获取 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
4

3 回答 3

1

你可能想试试

$db->lastInsertId();

... 反而。注意 中的小写d字母lastInsertId

参考文档

于 2013-04-07T22:31:06.740 回答
1

Now that I've had my coffee - you are creating the last insert statement BEFORE you populate the variables. I think this is what Maerlyn was hinting at

You need to move $queryUserJourney down below your 2 inserts.

于 2013-04-07T23:31:49.863 回答
0

@科林,

PDO's last insert id returns the value of an auto-increment primary key, if I'm not completely mistaken. It looks to me like $query's table doesn't have this

于 2013-04-07T22:36:25.077 回答