多个查询仅执行最后一个查询

时间:2017-04-11 13:25:06

标签: php mysql

我在下面有这个代码;

$sql = "SELECT * FROM tbl1 where id_no = '$id_no'";
    $result = $conn->query($sql);

     if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $new = $row['full_name'];
       header("location:new.php?msg=ID Number $id is already 
      Registered");
    }
    } else {
      $created = date('jS \ F Y h:i:s A');
        $tr_no = 'TR_'.rand(10000,99999).'/'.date(Y).'';

    include '../db_config/connection.php';

    //update tables
    $sql =  "INSERT INTO tbl2 (id,vehicle_id,policy_id,insured_by,insurance_co,value_insured,start_date,end_date,created)VALUES ('$tr_no','$reg_no','$p_id','$user_index','$co_id','$value_insured','$start_date','$end_date','$created')" ;
    $sql =  "UPDATE tbl1 SET updated='1' WHERE item_id = '$reg_no'";
    $sql =  "INSERT INTO tbl3 (doc_number,value,date,reg_no) VALUES('$tr_no','-$value_insured','$created','$reg_no'";

    if ($conn->query($sql) === TRUE) {
        header("location:new_insurance.php?message=ENTRIES SUCCESSFULLY POSTED");
    } else {
        $error = $conn->error;
         header("location:new_client.php?err=$error");
    }

    $conn->close();



    }
    $conn->close();

    ?>

包含插入和更新查询的最后一位是我遇到问题的地方。而不是执行所有三个查询,只执行最后一个查询。我应该包括哪些修改?

1 个答案:

答案 0 :(得分:0)

首先更改这些语句(连接$ sql变量并在每个语句的末尾添加分号';'。)

    $sql =  "INSERT INTO tbl2 (id,vehicle_id,policy_id,insured_by,insurance_co,value_insured,start_date,end_date,created) VALUES ('$tr_no','$reg_no','$p_id','$user_index','$co_id','$value_insured','$start_date','$end_date','$created');" ;
    $sql .=  "UPDATE tbl1 SET updated='1' WHERE item_id = '$reg_no';";
    $sql .=  "INSERT INTO tbl3 (doc_number,value,date,reg_no) VALUES('$tr_no','-$value_insured','$created','$reg_no');";

现在最终通过mysqli_multi_query()

执行多个查询
if (mysqli_multi_query($con,$sql)) {   //con is your connection
        header("location:new_insurance.......