我有4個MySQL錶帶有以下各項:如何從具有主鍵自動增量的表中將數據插入到具有外鍵的表中?
user
-user_id PK,AI
-user_name
-user_mobil
-user_passw
-user_email
bookingdetails
-booking_id PK,AI
-booking_date
-booking_time
-person_number
booking
-booking-_id FK
-restaurant_id CK
-user_id CK
restaurant
-restaurant_id PK
-restaurant_name
-restaurant_address
-restaurant_description
我想進行預訂,我插入所有bookingdetails數據,這給了我一個AI booking_id,以後我想提出我的預訂表並插入restaurant_id和user_id使用bookingdetails表給出的相同booking_id。
我作了如下的代碼實現在PHP上的LocalServer:
$booking_date=$_POST["booking_date"];
$booking_time=$_POST["booking_time"];
$number_of_place=$_POST["number_of_place"];
$customer_id=$_POST["customer_id"];
$restaurant_id=$_POST["restaurant_id"];
$res;
$sql_query = "INSERT INTO bookingdetails(booking_date, booking_time, number_of_place) VALUES ('$booking_date','$booking_time', '$number_of_place')";
$sql_query2 = "INSERT INTO `booking`(`booking_id`, `customer_id`, `restaurant_id`) SELECT booking_id, '$customer_id', '$restaurant_id' FROM bookingdetails ORDER BY booking_id DESC LIMIT 1 ;";
if(mysqli_query($con,$sql_query))
{
}
else
{
}
if(mysqli_query($con,$sql_query2))
{
}
else
{
}
?>
那是它加入到Android應用程序的服務器上的合法的解決方案嗎?有沒有任何情況下,我沒有得到第二個查詢的好身份證?什麼會是更好的解決方案?通過@馬克伍
使用在評論給出最後插入ID
使用最後插入的id,標準是你PK必須是AI。 mysqli_insert_id()函數返回在最後一個查詢中使用的id(由AUTO_INCREMENT生成)。資料來源:http://www.w3schools.com/php/php_mysql_insert_lastid.asp –
@Mark Ng,把它寫成答案,這個問題可以「解決」 – davejal
@davejal你可以在手機上寫下它 –