gpt4 book ai didi

php - 我想将数据从单个表单插入到多个表中,两个表都包含关系

转载 作者:行者123 更新时间:2023-11-30 00:49:26 25 4
gpt4 key购买 nike

我是 php 新手,正在尝试学习。我也在尝试制作一个网络应用程序“学校管理系统”。当我从同一表单在学生和家长表中插入记录时遇到问题,该表单正常,并且它在学生表中插入记录,但不在家长表中插入记录。在 parent 和学生表中,student_id 是通用的,在学生表中,student_id 包含主键,在 parent 表中,它包含外键。我的代码如下:

<小时/>
<?php>
if(isset($_POST['submit'])){
$reg = $_POST['reg_no'];
$s_name = $_POST['student_name'];
$s_father = $_POST['student_father'];
$p_last_name = $_POST['parent_lastname'];
$s_birth = $_POST['student_birth'];
$p_phone = $_POST['parent_phone'];
$p_address = $_POST['parent_address'];
$school_name = $_POST['school_name'];
$batch = $_POST['session_batch'];
//filtering variables
$reg_no = mysql_real_escape_string($reg);
$student_name = mysql_real_escape_string($s_name);
$student_father = mysql_real_escape_string($s_father);
$parent_last_name= mysql_real_escape_string($p_last_name);
$student_birth = mysql_real_escape_string($s_birth);
$parent_phone = mysql_real_escape_string($p_phone);
$parent_address = mysql_real_escape_string($p_address);
$school = mysql_real_escape_string($school_name);
$batch = mysql_real_escape_string($batch);
//connecting to db by including db file
include_once('include/dbconnect.php');

$db_select = mysql_select_db($server_db_name,$db_connect);
if ($db_connect)
{
$student_query = "INSERT INTO students (school_id, session_id, student_name,
student_father, student_birthdate, registration_no) VALUES
('$school','$batch','$student_name','$student_father','$student_birth','$reg_no')";
$s_query = mysql_query($student_query) or DIE ("error. while inserting records in
student");
/* here im trying to select student_id which is inserted above to insert data in
parents table*/
$id_query = mysql_query("SELECT * FROM students WHERE student_id = $student_name
LIMIT 1") or DIE ("Could complete the id query");
while ($id_result = mysql_fetch_array($id_query))
{ $s_id = $id_result['student_id'];
$parent_query = "INSERT INTO parents (school_id, student_id, parent_name,
parent_lastname, parent_phone, parent_address)
VALUES('$school','$s_id','$student_father','$parent_last_name',
'$parent_phone','$parent_address')";
$p_query = mysql_query($parent_query);
if (!$parent_query) { echo "error. while inserting records in student"; }
}
mysql_close($db_connect);
header('location:admin.php?student');
}
else {
echo "Error While Connecting to server";
}
}else {
header('location:admin.php?error');
}
?>

最佳答案

就像 JOE LEE 在上面的代码片段中提到的,

$generated_key=mysql_insert_id();

//这行代码实际上返回的是自动生成的 id,当然我猜你想要从学生表中自动递增的值作为父表。

关于php - 我想将数据从单个表单插入到多个表中,两个表都包含关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105790/

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