我已经使用PHP将HTML页面中的表单值插入到数据库中,但我必须将其与另一个表格相结合。一个查询将一些值插入地址表,这是有效的。从地址查询中提取MAXID值后,我必须使用它将其他值输入“staff”表。当我注释掉员工表查询时,它可以工作。当代码处于活动状态时,我收到此错误:
无法从sakila成功运行查询
(INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('Hunter', 'Norman', '', 'Test@mail.com', '2'))
:无法添加或更新子项 row:外键约束失败(sakila
。staff
,CONSTRAINTfk_staff_address
外键(address_id
)参考address
(address_id
)ON UPDATE CASCADE)
我以前曾帮助修复关联索引,但仍然有错误。这是代码:
$maxQuery = "SELECT MAX(address_id) FROM address";
$result = mysqli_query($connect, $maxQuery);
$row = mysqli_fetch_assoc($result);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
else
{
print ("<p>Max Address ID:".$row['MAX(address_id)']."</p>");
}
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id)
VALUES ('$first_name', '$last_name', '{$row[MAX(address_id)]}', '$email', '$store_id')";
$staffResult = mysqli_query($connect, $userQuery1);
if (!$staffResult)
{
die("Could not successfully run query ($userQuery1) from $db: " .
mysqli_error($connect) );
}
else
{
print(" <h1>New Staff Record Added!</h1>");
print ("<p>The following record was added:</p>");
print("<table border='0'>
<tr><td>First Name</td><td>$first_name</td></tr>
<tr><td>Last Name</td><td>$last_name</td></tr>
<tr><td>Email</td><td>$email</td></tr>
<tr><td>Store ID</td><td>$store_id</td></tr>
<tr><td>Address</td><td>$address</td></tr>
<tr><td>City</td><td>$city</td></tr>
<tr><td>District</td><td>$district</td></tr>
<tr><td>Postal Code</td><td>$postal_code</td></tr>
<tr><td>Phone</td><td>$phone</td></tr>
</table>");
}
答案 0 :(得分:1)
访问阵列时,您遗漏了一些引号。此外,假设FK是一个数字,查询中的引号是不必要的。
应该是:
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('$first_name', '$last_name', {$row['MAX(address_id)']}, '$email', '$store_id')";
提示:如果您var_dump()
$userQuery1
,您将看到它正在运行的内容。此外,如果您打开了PHP警告,您会看到它尝试使用常量执行PHP max()
函数,它假定它是一个字符串address_id
。