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