Hi all. I have run into a problem with inserting values into table.

I have 2 tables: PUBLISHER with fields: PUBLISHER_CODE (Primary Key) and PUBLISHER_NAME. BOOK table fields: PUBLISHER_CODE (Primary Key and Foreign key to PUBLISHER table) and TITLE.

The user enters bookCode and publisherName into 2 textboxes

Here is the code for inserting:

"INSERT INTO BOOK (TITLE) VALUES(@bookCode)";

"INSERT INTO PUBLISHER (PUBLISHER_NAME) VALUES(@publisherName)";

When running programme, the PUBLISHER table generates a new PUBLISHER_CODE (Primary Key) and publisherName inserted.

Now problem is for the BOOK table the following error appears:

"Cannot insert the value NULL into column 'PUBLISHER_CODE'", table BOOK

Why is this happening? Doesnt BOOK generate same/new PUBLISHER_CODE from PUBLISHER table since its a foreign key?

Why is your foreign key also your primary key for table Book?
What happens if a publisher has more than one book?

Typically the table structure you would see for this relationship is like this:

book_id (PK,auto_increment)
publicher_code (FK)
title

book_id will generate automatically when the record is inserted
publisher_code must be inserted manually and must reference a valid existing record in publisher table

Doesnt BOOK generate same/new PUBLISHER_CODE from PUBLISHER table since its a foreign key

No, you have to insert that value. Modify your book table to a design similar to what hearth listed above.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.