简体   繁体   English

未填充外键MySQL

[英]Foreign Key Not Populated MySQL

Foreign key not populating in child table with mysql. 未使用mysql在子表中填充外键。 Total newbie in all things programming and sql. 编程和sql方面的新手。 Creating Web site Form to populate person data using PHP/MYSQL which then launches a secondary Web Site Form to populate car maintenance data. 创建网站表单以使用PHP / MYSQL填充人员数据,然后启动辅助网站表单以填充汽车维护数据。 Problem is the Foreign Key from the Parent Table is not updating the Child table. 问题是来自父表的外键没有更新子表。 Any help is much appreciated. 任何帮助深表感谢。

Parent Table: 父表:

$sql = "CREATE TABLE persons 
(
Firstname CHAR(15),
Lastname CHAR(15),
Age INT,
PRIMARY KEY(Firstname)
)";

Child Table: 子表:

$sql = "CREATE TABLE cardata
(
CID INT NOT NULL AUTO_INCREMENT, 
Firstname CHAR(15) NOT NULL,  
Manufacturer CHAR(25),
Model CHAR(15),
Year INT,
`Oil Miles` INT,
`Oil Date` DATE,
`Rotation Miles` INT,
`Rotation Date` DATE,
PRIMARY KEY(CID),
FOREIGN KEY (Firstname) REFERENCES persons (Firstname)
ON  UPDATE CASCADE ON DELETE CASCADE
)";

Parent Table Insert: 父表插入:

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

Child Table Insert: 子表插入:

$sql="INSERT INTO cardata (Firstname,Manufacturer)
VALUES
('LAST_INSERT_ID()','$_POST[manufacturer]')";

It's because you are inserting a string. 这是因为您要插入字符串。 LAST_INSERT_ID() shouldn't be wrap with single quotes as this makes it string literal . LAST_INSERT_ID()不应用单引号引起来,因为这会使它成为字符串文字 Remove the single quotes and it will surely work. 删除单引号,它肯定会起作用。

$sql="INSERT INTO cardata (Firstname,Manufacturer)
VALUES (LAST_INSERT_ID(),'$_POST[manufacturer]')";

As a sidenote, the query is vulnerable with SQL Injection if the value( s ) of the variables came from the outside. 作为一个旁注,查询是脆弱的SQL Injection ,如果变量的值(一个或多个 )从外面走了进来。 Please take a look at the article below to learn how to prevent from it. 请查看下面的文章,以了解如何防止它。 By using PreparedStatements you can get rid of using single quotes around values. 通过使用PreparedStatements您可以摆脱在值周围使用单引号的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM