Php 如何为查询构建逻辑

Php 如何为查询构建逻辑,php,mysql,mysqli,Php,Mysql,Mysqli,我有两张表,分别是学生和资格。 我在student表中插入了数据。 现在我想根据学生表中生成的id在资格表中插入数据。 我试着用这种方式写我的查询 $sql = "INSERT INTO student (name,fathername,degreetitle) VALUES ('$name','$fathername','$degreetitle')"; $sql_combine = "SELECT user_id FROM student WHERE fathername = $fathe

我有两张表,分别是学生和资格。 我在student表中插入了数据。 现在我想根据学生表中生成的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");

}

为什么不起作用?

您需要在信息表中为学生表中的id字段添加一个新列。正如@Franz指出的,您应该使用last_insert_id()获取值,然后将其包含在信息表的insert中。这就是链接这两个表的方式

$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

正如我所说:最后一次插入救援id()

假设所有查询都正常工作。你的错误日志怎么说?它没有给出任何错误。它只是简单地在两个表中添加数据,但针对不同的ID。我认为您要查找的是ist,它返回最后一次插入的ID。@Franzgleichman我也尝试过,但没有找到所需的IDresult@FranzGleichmann$last\u id=mysqli\u insert\u id($conn)$sql_combine=“从学生中选择用户id,其中用户id=$last_id,父名=$fathername”$sql1=“在信息(用户id、单元格、电子邮件)中插入值(“$sql\u combine”、“$cell”、“$email”)”;我在dbsee中有一个名为user_id的列,在mysqli_insert_id()之后,我对@FranzYou的最后一个答案不需要选择。只需使用它返回的值。您的列类型是什么?仍然根据不同的ID在表中保存数据。我以前也发现了同样的结果:(你的表
student
是否设置了自动增量ID?也许你应该发布你的表结构,因为除了缺少自动增量之外,我无法想象最后一次插入ID()的可能性。)是的!两个表都有自动增量ID。接下来我该怎么做?好的。然后从信息中删除自动增量。它没有用,因为你不希望它有自己的ID,而是引用
学生的ID。别忘了偶尔修剪一下你的开发表