如何从具有主键自动增量的表中将数据插入到具有外键的表中?

时间:2015-11-28 17:05:02

标签: php mysql sql-insert

我有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

我想预订,我会插入所有预订详细信息数据,这会给我一个AI booking_id,之后我想要我的预订表并插入restaurant_id和user_id,并使用相同的booking_id给出预订详细信息表。

我在本地服务器的php中实现了以下代码:

 $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应用的服务器上的合法解决方案吗?有没有,我在第二个查询中没有得到好的身份证?什么是更好的解决方案?

1 个答案:

答案 0 :(得分:0)

@Mark Ng评论中给出的答案

使用最后一个插入ID,标准是你的pk必须是AI。

mysqli_insert_id()函数返回上次查询中使用的id(使用AUTO_INCREMENT生成)。

来源: w3schools.com/php/php_mysql_insert_lastid.asp

详细说明

您必须执行需要上次插入ID的查询,然后您可以访问使用

 $last_id = $conn->insert_id;

反过来您可以使用以下查询。

注意:

我看到你使用查询来使用插入查询的结果,但你的语法不正确(你遗漏了values