我想显示下面所有错误的列表,但它一次只显示一个错误,有谁知道为什么我的代码没有显示错误列表?下面是显示存储错误的数组的代码,说明没有错误时会发生什么的代码,以及说明有错误时会发生什么的代码。
<?php
$getcourseid = (isset($_POST['courseid'])) ? $_POST['courseid'] : '';
$getcoursename = (isset($_POST['coursename'])) ? $_POST['coursename'] : '';
$getduration = (isset($_POST['duration'])) ? $_POST['duration'] : '';
$errors = array();
if (!$getcourseid){
$errors[] = "You must enter in Course's ID";
}else if (!$getcoursename){
$errors[] = "You must enter in Course's Name";
}else if (!$getduration){
$errors[] = "You must select Course's Duration";
}
if(!$errors) {
$insertsql = "
INSERT INTO Course
(CourseNo, CourseName, Duration)
VALUES
(?, ?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("sss", $getcourseid, $getcoursename, $getduration);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
// don't use $mysqli->prepare here
$query = "SELECT CourseNo FROM Course WHERE CourseNo = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getcourseid);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbCourseId);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
}
if(empty($errors)) {
if ($numrows == 1){
$errormsg = "<span style='color: green'>Course " . $getcourseid . " - " . $getcoursename . " has been Created</span>";
$getcourseid = "";
$getcoursename = "";
$getduration = "";
}else{
$errormsg = "An error has occured, Course has not been Created";
}
} else {
if (count($errors) > 0)
{
foreach ($errors AS $Errors)
{
$errormsg = "{$Errors} <br>";
}
}
}
?>
**ADDITIONAL QUESTION:**
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td></td>
<td id='errormsg'>$errormsg</td>
</tr>
<tr>
<td>Course ID:</td>
<td><input type='text' name='courseid' value='$getcourseid' /></td>
</tr>
<tr>
<td>Course Name:</td>
<td><input type='text' id='nameofcourse' name='coursename' value='$getcoursename' /></td>
</tr>
<tr>
<td>Duration (Years):</td>
<td>{$durationHTML}</td>
</tr>
<tr>
<td></td>
<td><input type='submit' value='Create Course' name='createbtn' /></td>
</tr>
</table>
</form>";
echo $form;
上面的表格位于此问题顶部的 php 代码下方。现在发生的事情是验证错误列表都显示在表单的顶部。但我真正想要的是每个验证错误都低于它所指的表单功能。
例如,如果我没有填写课程 ID 文本输入,那么我希望验证错误"You must enter in Course's ID"
显示在课程 ID 文本输入下方。
如果我没有填写课程名称文本输入,那么我希望验证错误"You must enter in Course's Name"
显示在课程名称文本输入下方。
等等。为了做到这一点,需要对代码进行哪些更改?