debugging 尝试为MySQL表的外键列插入空值时出错[已关闭]

px9o7tmv  于 2023-03-03  发布在  Mysql
关注(0)|答案(1)|浏览(133)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

9小时前关门了。
Improve this question
我这学期在做一个网络项目。我遇到了一个问题。
这是我在MySQL中的coupon表,它有两个外键:thuonghieu_mathdanhmucsanpham_madm。这两个外键都设置为默认空值.

这是我的CouponModel中的代码块。

function themCoupon($macoupon, $tencoupon, $hinhanh, $soluongnhapvao, $soluonghientai, $tgbd, $tgkt, $dieukienkm, $giatrihoadon, $phantramgiam, $giamtoida, $math, $madanhmuc) // This function is used to add new coupon's information   
{         
$sql = "INSERT INTO coupon(macoupon, tencoupon, hinhanh, soluongnhapvao, soluonghientai, thoigianbatdau, 
thoigianketthuc, dieukiengiamgia, giatrihoadon, phantramgiam, giamtoida, thuonghieu_math, danhmucsanpham_madm) 
VALUES('$macoupon', '$tencoupon', '$hinhanh', '$soluongnhapvao', '$soluonghientai', '$tgbd', '$tgkt', 
'$dieukienkm', '$giatrihoadon', '$phantramgiam', '$giamtoida', '$math', '$madanhmuc')";
         
return mysqli_query($this->con, $sql);     
}

这是我用来插入一个新的优惠券的数据到优惠券表时,按下提交按钮在页面底部的形式。

如您所见,2个下拉选择框是2个外键danhmucsanpham_madm和thuonghieu_math的值选择。
这是我的HTML代码。

图中扫描的部分是为外键thuonghieu_math选择值的部分,第一个选项的值为空,其他的用while循环加载。
这是我的管理控制器文件。

上图是用于处理何时提交表单的代码块。第1059行和第1061行用于处理两个外键列之一的值为空时的情况。
我希望一切都不会出错,但是当我按照第二张图中的形式在我的coupon表中为外键列thuonghieu_math插入空值时,我在运行代码时遇到了这个错误。

但是如果我像这样直接插入到数据库管理系统中,就没有问题了。那么我错在哪里了呢?你能告诉我修复这个bug的方法吗?

svujldwt

svujldwt1#

本质上,这个错误意味着,您正在尝试添加一行到您的优惠券表,没有匹配的行(thuonghieu_math和danhmucsanpham_madm)出现在它的父表中。
要实现这一点,您必须插入到引用FK thuonghieu_math和danhmucsanpham_madm的父表中,然后继续使用两个父表的id来填充优惠券表

Foreign key relationships involve a parent table that holds the central
data values, and a child table with identical values pointing back to 
its parent. The FOREIGN KEY clause is specified in the child table.

It will reject any INSERT or UPDATE operation that attempts to 
create a foreign key value in a child table if there is no a 
matching candidate key value in the parent table.

Reference...

相关问题