首页 > 解决方案 > 在一个提交上更新多个表,将 id 从第一个表传递到第二个表

问题描述

我正在尝试通过一个表单更新 2 个表,表单提交到部件表,然后从插入的部件记录中获取 id,并在 job_parts 表中创建一个条目。

我已经尝试了各种论坛的几个选项,但到目前为止没有任何运气,我的代码和数据库结构一起在下面。

更新:按照建议编辑代码,但仅将数据发布到“parts”表而不是“job_parts 表”

表:!(https://drive.google.com/file/d/11I9HZrjc834_Ft5rqZoa0uFoJyDmmWGL/view?usp=sharing

if(isset($_POST['submitpart']))
{

    $job_id = $_POST['job_id'];
    $partName = $_POST['partName'];
    $partCost = $_POST['partCost'];
    $partRetail = $_POST['partRetail'];
    $partQuantity = $_POST['partQuantity'];

    $sql1 = "INSERT INTO parts (part_name, part_cost, part_rrp) VALUES ('$partName', '$partCost', '$partRetail');";
    $sql1 .= "SET @last_id_parts = LAST_INSERT_ID();";
    $sql1 .= "INSERT INTO job_parts (job_id, part_id, quantity) VALUES ('$job_id', @last_id_parts, '$partQuantity')";


    $outcome = mysqli_multi_query($conn, $sql1);
    if ($outcome) {
        do {
            // grab the result of the next query
            if (($outcome = mysqli_store_result($mysqli)) === false && 
 mysqli_error($mysqli) != '') {
                echo "Query failed: " . mysqli_error($mysqli);
            }
        } while (mysqli_more_results($mysqli) && 
 mysqli_next_result($mysqli)); // while there are more results
    } else {
        echo "First query failed..." . mysqli_error($mysqli);
    }

}

标签: phpmysql

解决方案


这种方法应该可以正常工作

    $sql1 = "INSERT INTO parts (part_name, part_cost, part_rrp) VALUES ('$partName', '$partCost', '$partRetail')";
    $result1=mysqli_query($con,$sql1);// where $con is connection string
    $last_id = mysqli_insert_id($con);// where $con is connection string
    $sql2 = "INSERT INTO job_parts (job_id, part_id, quantity) VALUES ('$job_id', $last_id , '$partQuantity')";
  $result2=mysqli_query($con,$sql2);// where $con is connection string

推荐阅读