dongmao9217 2017-07-27 19:38 采纳率: 100%
浏览 75
已采纳

在向数据库发送信息时出现网站表单问题

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.

  • 写回答

2条回答 默认 最新

  • dongtan1009 2017-08-30 18:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable