【发布时间】:2011-07-11 14:42:18
【问题描述】:
我创建了一个简单的表单,其中包含一些必填字段,如果未填写,则会将错误返回给用户,通知他们该字段是必填的。 由于有多个检查字段,它可以输出多个错误消息。
我想知道如何在我的表单上定义一个显示这些错误的区域,因为目前这些错误只是显示在表单的底部,除非你向下滚动页面,否则你看不到。
我可以定义我的错误显示在哪里吗?
这里是错误检查代码:编辑
Old code was here
过去有人建议我创建一个循环来一次检查一个错误,但我是 php 新手,所以不知道该怎么做。
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br/>";
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errors .="You did not select a tutor<br/>";
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errors .="You did not enter a procedure<br/>";
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errors .="You did not enter a grade<br/>";
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errors .="You did not enter a reflection<br/>";
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errors .="You must enter a reasan why you ticked the alert box";
}
//Code to check the password field is completed and correct
if (empty($_POST['password']))
{
$errors .="You did not enter you password";
}
if (!empty($_POST['password']))
{
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$masterpass = $_POST['password'];
$masterpass = htmlspecialchars($masterpass);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "username";
$pass_word = "password";
$database = "name of database";
$server = "server";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$masterpass = quote_smart($masterpass, $db_handle);
$SQL = "SELECT * FROM masterpass WHERE password = $masterpass";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
echo "";
}
else {
$errors .= "Password was not recognised";
exit();
}
}
mysql_close($db_handle);
}
}
if(!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
exit();
}
}
【问题讨论】:
-
请向我们提供此表单的完整 html 和 php,我可以提供帮助。仅给出执行错误检查的 php 部分并不能提供回答此问题所需的所有信息。
-
如果您使用适当的缩进,您会发现开发和调试代码更容易。
-
我建议使用某种形式的 javascript 直接向用户检查前端错误。仅使用 php 会变得非常混乱。