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.