问题
我有这个表单,管理员可以输入领导者的ID和最多6个学生ID。当管理员点击提交按钮时,我的PHP文件应验证输入中的信息,然后输入领导者的ID和数据库中的学生ID。但是当我测试程序时,程序会为学生ID插入NULL
。
小组表(从空白开始)
id | leaderID | studentID
PHP代码
<?php
require '../connect.php';
$leaderID = $_POST['leader-id'];
$students = array(
$_POST['student-id-1'],
$_POST['student-id-2'],
$_POST['student-id-3'],
$_POST['student-id-4'],
$_POST['student-id-5'],
$_POST['student-id-6'],
);
$studentSave = array();
// check if inputs are not empty
if(!empty($leaderID)) {
// loop through all students
foreach ($students as $student) {
// check if student is not empty
if(!empty($student)) {
// add student to new array
array_push($studentSave, $student);
}
}
// loop through all students
foreach ($studentSave as $student) {
// check if students exist
$getStudent = $link->prepare("SELECT * FROM students
WHERE studentID = ':student'");
$getStudent->execute(array(
"student" => $student
));
$getStudent->fetch();
// if student exist
if($getStudent) {
// insert them into the database
$insert = $link->prepare("INSERT INTO teams (leaderID, studentID)
VALUES (:leaderID, :studentID)");
$insert->execute(array(
"leaderID" => $leaderID,
"studentID" => $studentID,
));
if(!$insert) {
header("Location: ../../admin.php?msg=Sorry, we ran into an error");
} else {
header("Location: ../../admin.php?msgSuccess=Success");
}
} else {
header("Location: ../../admin.php?msg=A student doesn't exist");
}
}
} else if(empty($leaderID)){
header("Location: ../../admin.php?msg=There must be a leader");
}
?>
HTML表单
<div class="add_team">
<h1>Add Team</h1>
<form action="server/add/add_team.php" method="post">
<input type="text" name="leader_id" placeholder="* Leader ID">
<input type="text" name="student_id_1" placeholder="Student ID">
<input type="text" name="student_id_2" placeholder="Student ID">
<input type="text" name="student_id_3" placeholder="Student ID">
<input type="text" name="student_id_4" placeholder="Student ID">
<input type="text" name="student_id_5" placeholder="Student ID">
<input type="text" name="student_id_6" placeholder="Student ID">
<center>
<button type="submit" name="Add"><i class="fa fa-plus-circle fa-lg" aria-hidden="true"></i>Add</button>
</center>
</form>
</div> <!-- END OF .ADD_TEAM -->
所以我的程序循环遍历所有输入值并检查是否有任何输入不为空。然后程序将非空输入的值存储到新数组中。程序检查数据库中是否已存在值,最后将数据查询到数据库中。
答案 0 :(得分:0)
我的问题是变量$studentID
未定义,所以我应该使用$student
<强>代码强>
// insert them into the database
$insert = $link->prepare("INSERT INTO teams (leaderID, studentID)
VALUES (:leaderID, :studentID)");
$insert->execute(array(
"leaderID" => $leaderID,
"studentID" => $student,
));