通过 PDO 分配外键 SQL

Assigning Foreign Key through PDO SQL

目前我要table关注,它是一个酒店预订网站;第一个 table 是客人,另一个是预订。这些 table 由约束链接,主键是客人 table 上的客人 ID,外键是预订 table.

上的 GuestIDFK2

为了通过预订识别房客table,需要将外键放在那里。问题是我不知道如何通过 PDO 分配外键,因为我不知道从哪里获取信息。 (我的意思是确定我可以为其分配一个值,但是我从哪里获得信息)?我可以将它存储在会话变量或其他东西中吗?

我的连接和第一个查询代码如下。这会分配一个自动递增 ID,但我不知道如何在执行第二个查询时将其复制到 FK。

<?php
//Connecting to db adding customer
$conn = new PDO("mysql:host=localhost;dbname=sgh_bookings","root","");
if(isset($_POST['submit'])){
$resultquery1 = $conn->prepare("INSERT INTO `guests` VALUES ('','$_SESSION[cusfname]','$_SESSION[cusaddress]','')");
$resultquery1->execute();
$resultquery2 = $conn->prepare("INSERT into ``");
}
?>

向客人插入数据后 table,然后选择最后插入的 ID 并将其插入预订 table 示例:

<?php
//Connecting to db adding customer
$conn = new PDO("mysql:host=localhost;dbname=sgh_bookings","root","");
if(isset($_POST['submit'])){
$resultquery1 = $conn->prepare("INSERT INTO `guests` VALUES ('','$_SESSION[cusfname]','$_SESSION[cusaddress]','')");
$resultquery1->execute();
$id = $conn->lastInsertId();
//insert the $id in following table
$resultquery2 = $conn->prepare("INSERT into ``");
}
?>

从手册页 here 无耻地挖走。相应地调整。直接使用 $theGuest 之类的变量或会话变量。使用 bindParam,无论如何你都在 PDO,利用它 :>

如果你正在使用PDO,请使用PDO。

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>