Mr E
Mr E

Reputation: 33

Website form issues when sending information to database

I will try and explain this in the best way possible. So I have a database with 3 tables: customers , login and address and they look like this:

customerID
first_name
last_name
email
phone
login_fk
address_fk

loginID
username
password

addressID
housenumber
streetname
postcode
city

Code:

$query = "INSERT INTO customers ". "(first_name,last_name,phone,email) ". "VALUES('$fname','$sname','$phone','$email');"; 
$result = mysqli_query($conn, $query) or die(mysqli_error($conn)); 

My webform sends the login details and address details to the database no problem. However I get this message and nothing sends to the customers table:

Cannot add or update a child row: a foreign key constraint fails (database1.customers, CONSTRAINT customers_ibfk_1 FOREIGN KEY (login_fk) REFERENCES login (loginID) ON UPDATE CASCADE)

I am assigning values to all fields (using the webform) except the primary keys which are auto-incremented and the fk values. I assume this message is being brought up because I am not setting fk values or am i wrong? If I am correct, how do I take the values from the other tables to ensure the relationship is correct? ie login_fk and loginID have a relationship and the IDs should be the same and the same with the address_fk and addressID fields. If I use the database to insert values then the relationships are fine because I am manually assigning the fk values to match the loginID and addressID so I am assuming the database is fine and I just need to use php to take the ID from login and address and send it to the customer table fk values? I have worked with databases on many occasions and I have worked with php and html websites on many occasions but this is my first attempt at creating a dynamic website so I do apologise if this is a silly question but hoping it will teach me a bit more and others may have this same issue when it comes to creating dynamic websites.

Upvotes: 0

Views: 59

Answers (2)

Vikash Kumar
Vikash Kumar

Reputation: 186

It's all about Primary key , candidate key and Foreign key concept. Here the field "login_fk" declared in your "customers" table which is a child table and the field "loginID" as a primary key declared in Login table which is your Reference table / Parent Table. So at first you will have to insert data into "Login" table(parent table) after than it will allow you to insert data into "cusomers" table.

for more details about Primary key and Foreign key, you can visit at https://www.w3schools.com/sql/sql_foreignkey.asp

Upvotes: 1

PotatoManager
PotatoManager

Reputation: 1775

Insert your loginid and password in login table first and then run the insert query on customers so thatvyour foreign key does not fail

Upvotes: 0

Related Questions