在while循环php中向表单添加验证检查
我有一个表单显示如下: 事件名称:下拉菜单 我试图添加一个检查,通过从下拉菜单中选择,确保while循环生成的每个事件都有一个学生分配给它 我已经尝试为这个添加一个检查,但它并没有什么不同-它加载表单操作页面“savecompetitors” 到目前为止,我已经为php编写了以下内容:在while循环php中向表单添加验证检查,php,forms,validation,while-loop,Php,Forms,Validation,While Loop,我有一个表单显示如下: 事件名称:下拉菜单 我试图添加一个检查,通过从下拉菜单中选择,确保while循环生成的每个事件都有一个学生分配给它 我已经尝试为这个添加一个检查,但它并没有什么不同-它加载表单操作页面“savecompetitors” 到目前为止,我已经为php编写了以下内容: <?php session_start(); require_once 'db/connect.php'; require_once 'db/checkuserloggedin.php'; include
<?php
session_start();
require_once 'db/connect.php';
require_once 'db/checkuserloggedin.php';
include 'db/header.php';
echo $_SESSION['Username'] . ' logged in successfully';
echo '<h3> Entry form </h3>';
//Query to display all events
if ($event_result = $con->query("SELECT Name FROM event")) {
echo "<form method =\"POST\" action=\"savecompetitors.php\">";
echo '<table>';
while ($row = $event_result->fetch_assoc()) {
echo '<tr>';
echo '<td>';
echo $row['Name'] . ' ';
echo '</td>';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Forename, Surname, Student_ID " .
"FROM student, teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")
) {
if ($student_result->num_rows) {
echo '<td>';
echo "<select name ='" . $row['Name'] . "'>";
while ($row1 = $student_result->fetch_assoc()) {
echo '<option value="" style="display:none;"></option>';
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
if (isset($_POST['submit'])) {
if (empty($_POST['Student_ID'])) {
$error = 'A student must be selected for every event';
}
}
}
echo "</select>";
echo '</td>';
echo '</tr>';
}
}
}
echo '</table>';
echo '<input type="submit" name="submit" value ="Submit" >';
echo '<input type="reset" value ="Reset">';
echo '<span class="error"><?php echo $error;?></span>';
echo '<span class="error"><?php echo $success;?></span>';
echo "</form>";
} else {
echo 'No student records available';
}
savephp:
<?php
require_once 'db/connect.php';
$error = '';
$success = '';
$event_result = $con->query("SELECT Event_ID, Name from event");
while ($row = $event_result->fetch_assoc()) {
$eventname = str_replace(' ', '_', $row['Name']);
print_r($row);
$con->query("INSERT INTO competitors (Event_ID, Student_ID) VALUES (" . $row['Event_ID'] . ", " . $_POST[$eventname] . ") ");
$success = 'Entry form has been successfully saved and students are entered as competitors for their submitted events';
}
考虑把这个代码分解成离散函数。使其更易于维护和阅读。没有人喜欢读七级缩进。此外,在查询中插入超全局变量而不进行清理会使您容易受到SQL注入的影响。@Gordon对缩进问题表示抱歉。这个表单只有下拉菜单来选择表单,所以不需要sql注入,关于这个验证检查有什么想法吗?你有什么样的表单是不相关的。发送到服务器的内容才是最重要的。@Gordon但真正的转义字符串和带斜杠可以解决这个问题。另外,他们如何将输入注入下拉列表,我误解了这个概念。一个比真正的转义字符串和带斜杠更好的选择是使用准备好的语句。你的表格很容易被篡改。它位于客户端,使用浏览器的开发工具更改它的选项值很简单。但更重要的是,它不需要表单向服务器发送带有任意值的http请求,例如使用cURL。这就是为什么您应该将脚本的所有输入视为潜在恶意