插入两个表的外键和主键

时间:2018-05-24 08:51:09

标签: php mysql

我的数据库中有两个表,reservationsguests。行如下:

预订

  • 预订ID
  • Property Id
  • 签到日期
  • 结帐日期
  • 价格

访客

  • 访客ID
  • 预订ID
  • 访客姓名
  • 访客地址

使用包含预订详细信息和客人详细信息的表单。

如何运行insert查询,以便同时将自动生成的预留ID(数据库中的自动增量)插入到guest虚拟机表中?

这是我到目前为止所拥有的。我使用last_insert_id()

更改了我的代码
INSERT INTO reservations
   SET Checkin date= '24/05/2018', checkout date = '29/05/2018';
INSERT INTO guests 
   SET reservation id = LAST_INSERT_ID(), 
       guest name = guest name

3 个答案:

答案 0 :(得分:1)

首先,您可以根据最后插入的ID将数据插入Reservation表中,您可以使用表Guest的列的值。另外,请保持外键约束,以便在保留的更新和删除操作时,在Guest表上执行同时操作。 要获取最后插入的ID,

 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }

 $sql = "INSERT INTO ...";
 if ($conn->query($sql) === TRUE) {
   $last_id = $conn->insert_id; //gives the last inserted id
 }   

答案 1 :(得分:1)

首先插入预订表

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


$sqlR = "INSERT INTO Reservation(firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
$rStatus = $conn->query($sqlR);
$res_id = $conn->insert_id;
$sql = "INSERT INTO MyGuests (firstname, lastname, email,res_id)
VALUES ('John', 'Doe', 'john@example.com',$res_id)";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

答案 2 :(得分:1)

首先使用insert_id函数运行insert查询,然后使用该insert_id运行第二个插入查询