mysqli_insert_id的问题

时间:2014-10-02 21:35:15

标签: php mysql sql mysqli

我正在尝试在多个查询中使用mysqli_insert_id,但我不断获得Cannot add or update a child row: a foreign key constraint fails。以下是我的代码:

$con=mysqli_connect("Stuff");
            if(mysqli_connect_errno()){
                echo "There was a mistake connecting". mysqli_connect_errno();
                }
        $First=mysqli_real_escape_string($con,$_POST["FirstName"]);
        $Last=mysqli_real_escape_string($con, $_POST["LastName"]);
        $Phone=mysqli_real_escape_string($con,$_POST["Number"]);
        $Product=mysqli_real_escape_string($con,$_POST["Product"]);
        $Quantity=mysqli_real_escape_string($con,$_POST["Quantity"]);


            if(!empty($_POST["FirstName"]) && !empty($_POST["LastName"])){
                $sql="INSERT INTO Customer(First,Last)
                    VALUE('$First', '$Last')";
                    $id = mysqli_insert_id($con);
                        if(!mysqli_query($con,$sql)) {
                            die("ERROR". mysqli_error($con));

                                }
                            }


            if(!empty($_POST["Number"])){
                $sql="INSERT INTO Customer_Number(Customer_ID,Number)
                    VALUE('$id','$Phone')";

                        if(!mysqli_query($con,$sql)) {
                            die("ERROR". mysqli_error($con));

                                }
                            }

                            if(!empty($_POST["Product"]) && !empty($_POST["Quantity"])){
                                $sql="INSERT INTO Product(Customer_ID,Product,Quantity)
                                      VALUE('$id','$Product','$Quantity')";


                                     if(!mysqli_query($con,$sql)) {
                            die("ERROR". mysqli_error($con));

                                }else{
                               echo "Special Order Added";
                               }
                            }
                            mysqli_close($con);
                            ?>

我也尝试过使用Last_Insert_ID(),但这只适用于一个查询,然后当我尝试将其添加到第二个时,会给我相同的错误消息。

1 个答案:

答案 0 :(得分:1)

在mysqli_query

之后调用mysqli_insert_id