user1050632
user1050632

Reputation: 668

Foreign key solving

I'm working on creating two different tables with foreign keys on one of them.

I need to relate the sender and receiver from mailbox table, to users.item1

When I try my code, I get an error of:

Check the syntax for your version of MySQL

Which I did, I'm running 5.5.25

The manual shows an example which I tried, and I still get an error.

$sql="CREATE TABLE users(
    id INT NOT NULL AUTO_INCREMENT,
    item1 VARCHAR(32),
    item2 VARCHAR(32),password VARCHAR(32),
    PRIMARY KEY (id))";

if ($query = mysqli_query($con,$sql))
    echo "Table users created successfully";
else
    echo "Error creating table: " . mysqli_error($con);

$sql = "CREATE TABLE mailbox(
    id INT NOT NULL AUTO_INCREMENT, 
    item VARCHAR(32), 
    subject VARCHAR(32), 
    item  VARCHAR(64), 
    sender VARCHAR(32), 
    receiver VARCHAR(32), 
    item INT, PRIMARY KEY (id)
    FOREIGN KEY (id) REFERENCES users(id))";

Upvotes: 1

Views: 72

Answers (1)

John Woo
John Woo

Reputation: 263723

..I need to relate the sender and receiver from mailbox table, to the users table item1..

CREATE TABLE users
(
    id INT NOT NULL AUTO_INCREMENT,
    item1 VARCHAR(32),
    item2 VARCHAR(32),
    password VARCHAR(32),
    PRIMARY KEY (id),
    KEY(item1)
);

CREATE TABLE mailbox
(
    id INT NOT NULL AUTO_INCREMENT, 
    item VARCHAR(32), 
    subject VARCHAR(32), 
    sender VARCHAR(32), 
    receiver VARCHAR(32), 
    PRIMARY KEY (id),
    CONSTRAINT tb_fk1 FOREIGN KEY (sender)
        REFERENCES users(item1),
    CONSTRAINT tb_fk2 FOREIGN KEY (receiver)
        REFERENCES users(item1)
)

follow-up question: why do you have 3 columns with name item on table mailbox?

Upvotes: 1

Related Questions