可以根据条件生成多个记录吗?

时间:2016-11-24 00:03:45

标签: php mysql sql

对于SQL来说,我是新手,所以请原谅我对这个问题的无知。我有一个包含PassengerBookingBooking_DetailsTicket表格的数据库。

在预订表中,我有一个名为noOfPassengers的属性。我想实施一种情况,其中乘客为其家人预订门票,使得一个预订ID(在预订表中)将在乘客和票证表中生成多个记录,这取决于numberOfPassenger是否> 1.

我如何在SQL中完成此操作?我知道表之间需要一些连接,但我不确定SQL命令的结构。

1 个答案:

答案 0 :(得分:0)

你会在php而不是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

您实际上并不需要存储乘客数量,您可以使用查询轻松找到;

此代码也可能有错误。但是你应该能够将它作为一个起点。