php - 在一个提交上更新多个表,将 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);
}
}
解决方案
这种方法应该可以正常工作
$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
推荐阅读
- window - 为什么 sweetalert2 在父窗口中打开,而不是在新打开的 blanc 窗口中
- html - 如何在 div 中居中多个 div
- google-apps-script - 无法授予对 Google 应用脚本的访问权限
- java - 如何在另一个服务中调用这个存储库的功能?
- python - 如何检查列表中是否有整数
- python - 有没有办法从已经解决的表达式中返回变量?
- openstack - openstack 发出一个没有过期时间的令牌
- sql - 在 PostgreSQL 中将时间转换为十进制数据类型
- proxy - Windows Server Core 2022 - 使用用户/密码添加代理
- nginx - 使用 nginx 正则表达式的位置