使用PHP在foreach数组中设置INT外键列为NULL


Setting an INT foreign key column to NULL in a foreach array using PHP

我有一个带有附加表的表单,它继续将表单中输入的值附加到表中,当我单击Save按钮时,整个记录集将进入表…

Controller页面:-

function invoiceEntry(){
    $ref_invoice_no=$_POST['ref_invoice_no'];
    $entry_date=$_POST['entry_date'];
    $store_name=$_POST['store_name'];
    $store_name=empty($_POST['store_name']) ? NULL : $_POST['store_name'];
    $no_packages=$_POST['no_packages'];
    $net_weight_each=$_POST['net_weight_each'];
    $total_net_qty=$_POST['total_net_qty'];
    $obj=new Sales();
    foreach ($ref_invoice_no as $key => $value) {
        $obj->addInvoice($ref_invoice_no[$key],$entry_date[$key],$store_name[$key],$no_packages[$key],$net_weight_each[$key],$total_net_qty[$key]);
    }
}

Model页:-

function addInvoice($ref_invoice_no,$fregno,$entry_date,$catalogue_type,$store_name,$category,$grade,$pack_type,$manufacture_date,$full_half,$sample_allowed,$no_packages,$net_weight_each,$total_net_qty){
        $conn=new Connection();
        $sql="INSERT INTO invoice (ref_invoice_no,fac_reg_no,date_of_entry,exestate_mainsale,stores_code,category_code,grade_code,packing_code,date_of_manufacture,full_half,sample_allowed,no_of_packages,net_weight_each,total_net_qty) VALUES('$ref_invoice_no','$fregno','$entry_date','$catalogue_type',$store_name,'$category','$grade','$pack_type','$manufacture_date','$full_half','$sample_allowed','$no_packages','$net_weight_each','$total_net_qty')";
        echo $sql;
        $result=$conn->query($sql);
        return $result;
}

我得到的错误是:-不能添加或更新子行:外键约束失败(teabsinvoice,约束invoice_ibfk_2外键(stores_code)引用stores (stores_code))

但是如果我去,并在PHPMyAdmin的查询,它的工作完美,因为我已经设置的商店字段接受NULL值

这是错误的,因为store_name是一个数组,您需要检查索引。此代码永远不会设置为null。

$store_name=empty($_POST['store_name']) ? NULL : $_POST['store_name'];

改为:

$store_name=$_POST['store_name'];

您需要将该逻辑移动到:

$obj->addInvoice($ref_invoice_no[$key],$entry_date[$key],empty($store_name[$key]) ? NULL : $store_name[$key],$no_packages[$key],$net_weight_each[$key],$total_net_qty[$key]);