简体   繁体   中英

How to pass foreign key for creating table in php

Here is my two tables, I want to pass my guest_id as a foreign key inside reservation table. but it's given error..

$sql = "CREATE TABLE MyGuests (
    guest_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";

// // sql to create table

$sql = "CREATE TABLE reservation (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FOREIGN KEY(guest_id) REFERENCES MyGuests(guest_id),
room INT(11) NOT NULL,
price FLOAT(11) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

where is the problem?

You need also add the column guest_id to your table reservation

Like:

$sql = "CREATE TABLE MyGuests (
    guest_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";

// // sql to create table

$sql = "CREATE TABLE reservation (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
guest_id INT(6) UNSIGNED,
room INT(11) NOT NULL,
price FLOAT(11) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY(guest_id) REFERENCES MyGuests(guest_id)
)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM