user2127632
user2127632

Reputation: 45

mysql inserting into 2 tables at once that have primary key and foreign key

I have two tables

books table

bookAwards table

ID of bookAwards is foreign key of ID in books table.

How can I insert into books table at the same time into bookAwards table?

When I am trying to insert into books table it gives the error that foreign key causes?

I want to insert into books table the values and then an awardname with a year into bookAwards?

Any help will be much appreciated.

Upvotes: 2

Views: 7244

Answers (1)

John Woo
John Woo

Reputation: 263723

You can use STORED PROCEDURE on this so you will only call once from the application level. Example,

DELIMITER $$
CREATE PROCEDURE InsertBook
(
    IN _Title INT,
    IN _AwardName VARCHAR(35),
    IN _Year INT
)
BEGIN
    INSERT INTO Books (Title)
    VALUES(_Title);

    -- since the ID is set as AUTO_INCREMENT
    -- there are two ways to do how you can get the ID 
    -- from the Books Table and insert it 
    -- on BookAwards

    -- FIRST WAY
    -- by using LAST_INSERT_ID()
    SET @last_ID = LAST_INSERT_ID();

    -- SECOND WAY
    -- by using MAX()
    -- SET @last_ID = (SELECT MAX(ID) FROM Books);


    INSERT INTO BookAwards(ID, AwardName, Year)
    VALUES (@last_ID, _AwardName, _Year);
END $$
DELIMITER ;

And on the application level or on any sources that you want to call this procedure,

CALL InsertBook('Lost Art', 'Best in Churva', 2013);

For security purposes, you can still parameterized the procedure, eg

CALL InsertBook(?, ?, ?);

Upvotes: 2

Related Questions