你會這樣做,而不是SQL。下面是一個例子:
<?php
//connect to dbh
$dbh = new PDO($dsn, $user, $password);
/**
* @param array $data
*/
function addBooking($data)
{
global $db;
$booking_id = false;
//add any other fields you have too.
$sth = $db->prepare('INSERT INTO Bookings (name,date)
VALUES (:name,:date);');
$sth->bindParam(':name', $data['name'], PDO::PARAM_STR);
$sth->bindParam(':date', $data['name'], PDO::PARAM_STR);
// and bind any other fields you have.
if ($sth->execute()) {
$booking_id = intVal($db->lastInsertId());
$sql = '';
$failed = false;
foreach ($data['passengers'] as $key => $passenger) {
//add any other fields you have too.
$sth = $db->prepare('INSERT INTO Passengers (name,booking_id)
VALUES (:name,:booking_id);';
$sth->bindParam(':name', $passenger['name'], PDO::PARAM_STR);
$sth->bindParam(':date', $booking_id, PDO::PARAM_INT);
// and bind any other fields you have.
$sth->execute();
}
}
return $booking_id;
}
function getBooking($booking_id)
{
global $db;
//add any other fields you have too.
$sth = $db->prepare('
SELECT
Bookings.name as booking_name,
Bookings.date as booking_date,
Passengers.* FROM Bookings
RIGHT JOIN Passengers on Bookings.id = Passengers.booking_id
WHERE Bookings.id = :id;');
$sth->bindParam(':id', $booking_id, PDO::PARAM_INT);
$result = $sth->fetch(PDO::FETCH_ASSOC);
$booking = array(
'name' => $result[0]['booking_name']]],
'name' => $result[0]['booking_date']]],
'passengers' => array()
);
foreach ($result as $row) {
if (isset($row['name'])) {
$booking['passengers'][] = array(
'name' => $row['name']
);
}
}
return $booking;
}
/**
* Usage
*/
$data = array(
'name' => 'Taxi',
//other data here too
'passengers' => array(
'name' => 'Antony'
//other data here too
)
);
$booking_id = addBooking($data);
$booking = getBooking($booking_id);
所以,你需要這樣的事情對你的表結構
Passengers
id | name | booking_id
Bookings
id | name | date
你實際上並不需要存儲乘客的數量,你可以發現,很容易出使用一個問題;
此外,此代碼可能有錯誤。但你應該能夠以此爲出發點。
這通常會在應用程序級別或通過使用「while」循環的存儲過程完成。 –
如果你向我們展示ERD會更好...... – barudo
你可以通過一個'INSERT' /'SELECT'生成多行,其中後者可以或不可以成爲'JOIN'的一部分......你想讓我顯示你舉個例子嗎? – Drew