通过PDO SQL

时间:2015-09-12 13:58:49

标签: php mysql sql pdo phpmyadmin

目前我需要关注的表格,它是一个酒店预订网站;第一张桌子是客人,另一张是预订。这些表通过约束链接,主键是来宾表上的访客ID,外键是预订表上的GuestIDFK2。

为了通过预订表识别客人,需要将FOREIGN KEY放入其中。问题是我不知道如何通过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 ``");
}
?>

2 个答案:

答案 0 :(得分:2)

将数据插入到来宾表后,然后拍摄最后插入的ID并将其插入到预订表中 例如:

<?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 ``");
}
?>

答案 1 :(得分:1)

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

如果您使用的是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();
?>