gpt4 book ai didi

php - MYSQL。向不同表插入数据失败

转载 作者:行者123 更新时间:2023-11-29 21:51:16 25 4
gpt4 key购买 nike

我正在构建一个 .php 以将数据插入到两个不同的表中。我已经使用了 mysqli_multi_query() 函数和 mysqli_insert_id(),但是,只有提交的数据只出现在其中一张表中。我已经陷入这个障碍几天了,任何人都可以帮我找出我的代码有什么问题吗?

这是 2 个表:

表患者:患者ID(PK)(AI),姓名,年龄,电子邮件,手机......

表emergency_contact:id(PK)(AI)、病人_id(FK)、姓名、关系、手机

    <?php
session_start();
?>
<?php

$pname=$_POST['pname'];
$pid=$_POST['pid'];
$hkid=$_POST['hkid'];
$dob=$_POST['dob'];
$age=$_POST['age'];
$gender=$_POST['gender'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
$address=$_POST['address'];
$ename=$_POST['ename'];
$relationship=$_POST['relationship'];
$emobile=$_POST['emobile'];

$con = new mysqli("localhost","root","2013700910","2013700910");

$last_id = $con->insert_id;

if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";

$sql="INSERT INTO patients (name, hkid, date_of_birth, age, gender, mobile, email, address)
VALUES('$pname', '$hkid' ,'$dob' ,'$age', '$gender', '$mobile', '$email', '$address');
INSERT INTO products (name, relationship, mobile, patient_id)
VALUES('$ename', '$relationship', '$emobile', '$last_id')";

if ($con->multi_query($sql) === TRUE) {

echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}

$con->close();

?>

(P.S. *仅 '$pname', '$hkid' ,'$dob' ,'$age', '$gender', '$mobile', '$email', '$address' 成功插入数据库。)

最佳答案

我还没有开始编写代码,但我认为你必须分开查询。你可以这样做:

        $sql="INSERT INTO patients (name, hkid, date_of_birth, age, gender, mobile, email, address) 
VALUES('$pname', '$hkid' ,'$dob' ,'$age', '$gender', '$mobile', '$email', '$address')";
if (!$con->query($sql)) {
echo "insert failed, error: ", $com->error;
} else {
$last_id = $con->insert_id;
$sql="INSERT INTO products (name, relationship, mobile, patient_id)
VALUES('$ename', '$relationship', '$emobile', '$last_id')";
$con->query($sql);
...
}

PS:很抱歉,格式不正确。

关于php - MYSQL。向不同表插入数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com