我有两张名为学生和资格的表。 我在学生表中插入了数据。 现在我想根据学生表中生成的id在资格表中插入数据。 我试图用这样的方式写我的查询
$sql = "INSERT INTO student (name,fathername,degreetitle)
VALUES ('$name','$fathername','$degreetitle')";
$sql_combine = "SELECT user_id FROM student WHERE fathername = $fathername";
$sql1 = "INSERT INTO information (user_id,cell,email)
VALUES ('$sql_combine','$cell','$email')";
if(mysqli_query($conn, $sql) && mysqli_query($conn, $sql1) && mysqli_query($conn, $sql_combine))
{
header("Location: successful_message.php");
}
为什么这不起作用?
答案 0 :(得分:3)
$sql1 ="INSERT INTO student (name,fathername,degreetitle)
VALUES ('$name','$fathername','$degreetitle')";
$sql2 = "SELECT last_insert_id() as id";
mysqli_query($conn, $sql1); //here you insert
$res = mysqli_query($conn, $sql2); //here you fetch the ID you inserted
$id = mysqli_fetch_array($res)['id'];
$sql3 = "INSERT INTO information (user_id,cell,email)
VALUES ('$id','$cell','$email')"; //here you use that said ID in your second query
mysqli_query($conn, $sql3); //aaand you insert
正如我所说:last_insert_id()救援
答案 1 :(得分:0)
您需要在信息表中为学生表中的id字段添加新列。正如@Franz指出的那样,你应该使用last_insert_id()来获取值,然后将其包含在信息表的插入中。这就是你链接这两个表的方式。