简体   繁体   English

在同一页面上显示PHP表单验证结果

[英]Display PHP Form Validation Results on Same Page

I'm sure the initial reaction is going to be something like, "Doesn't this guy have Google?" 我敢肯定,最初的反应将会是这样的,“难道这个家伙没有谷歌吗?” Yes, I'll admit this does seem like a pretty basic concept and I've tried and tried to wrap my head around it, looked up all manner of posts and articles on the topic, etc., but all to no avail. 是的,我承认这看起来确实是一个非常基本的概念,我试过并试图绕过它,查看关于这个主题的各种帖子和文章等等,但都无济于事。 Perhaps you can point me in the right direction? 也许你可以指出我正确的方向?

I have a basic contact form (contact.html) that I run with an external PHP script (contact.php). 我有一个基本的联系表单(contact.html),我使用外部PHP脚本(contact.php)运行。 Here's the HTML form code: 这是HTML表单代码:

<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
</div>
</form>

The PHP script validates that all of the fields were entered and then processes the form: PHP脚本验证输入了所有字段,然后处理表单:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//Validate the name:
if (!empty($_POST['name'])) {
    $name = $_POST['name'];
} else {
    echo "You forgot to enter your name.<br>";
}

//Validate the school:
if (!empty($_POST['school'])) {
    $school = $_POST['school'];
} else {
    echo "You forgot to enter your school.<br>";
}

//Validate the e-mail:
if (!empty($_POST['email'])) {
    $email = $_POST['email'];
} else {
    echo "You forgot to enter your e-mail.<br>";
}

//Validate the message:
if (!empty($_POST['message'])) {
    $message = $_POST['message'];
} else {
    echo "You forgot to enter a message.";
}

if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
    $phone = $_POST['phone'];
    $body = "$name\n$school\n$phone\n$email\n\n$message";
    mail("***", "PAL Website - Message from a Visitor", $body);
    header("Location: confirm.html");
}

}

?>

Everything works great and the form is validated and processed as intended. 一切都很好,表格按预期进行验证和处理。 However, I REALLY want to set it up so that the error messages are displayed on the same page or at least have the form refreshed with the error messages included. 但是,我真的想要设置它,以便错误消息显示在同一页面上,或者至少刷新表单并包含错误消息。

I've seen this done in other demonstrations (Larry Ullman's book, for example), but still can't quite figure out how to make it happen. 我已经在其他演示中看到了这一点(例如Larry Ullman的书),但仍然无法弄清楚如何实现它。 Can you please offer advice? 你能提出建议吗? What's the simplest way to go about it? 什么是最简单的方法呢?

Here's the page URL, if it helps: http://www.712jefferson.org/pal/contact.html 这是页面URL,如果它有帮助: http//www.712jefferson.org/pal/contact.html

Thank you! 谢谢!

I'd use jQuery for this. 我会使用jQuery。 Modifications to be made: 修改:

in HTML: add id to your input fileds, so you can "grab" them with jQuery (You can see the usage in the $.post method below). 在HTML中:为您的输入文件添加id,因此您可以使用jQuery“抓取”它们(您可以在下面的$.post方法中查看用法)。

<form id="form1" action="contact.php" method="post">
   <div class="form1">
      <label>Your Name:</label>
      <span><input id="name" type="text" name="name" /></span>
   </div>
   <div class="form1">
      <label>Your School:</label>
      <span><input id="school" type="text" name="school" /></span>
   </div>
   <div class="form1">
      <label>Phone Number:</label>
      <span><input id="phone" type="text" name="phone" /></span>
   </div>
   <div class="form1">
      <label>E-Mail Address:</label>
      <span><input id="email" type="text" name="email" /></span>
   </div>
   <div class="form3">
      <span><textarea id="message" cols="1" rows="1" name="message"></textarea></span>
   </div>
   <div class="wrapper">
      <input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
   </div>
</form>

in PHP: if there is no error in validation echo this: "success" 在PHP中:如果验证中没有错误,请回复:“成功”

if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
    echo "success";
    $phone = $_POST['phone'];
    $body = "$name\n$school\n$phone\n$email\n\n$message";
    mail("***", "PAL Website - Message from a Visitor", $body);
    header("Location: confirm.html");
}

Attach jQuery library to your site and use the code below in your HTML file inside brackets or in an external *.js file attached to Your site. jQuery库附加到您的站点,并在括号内的HTML文件或附加到您站点的外部* .js文件中使用下面的代码。 In Your HTML file's section use this: 在您的HTML文件的部分中使用:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

jQuery script: jQuery脚本:

$('#form1').submit(function() {
    event.preventDefault(); 
    $.post("contact.php", {name: $("#name").val(), school: $("#school").val(), phone: $("#phone").val(), email: $("#email").val(), message: $("#message").val()}, function(data){
        if(data !="success"){
            alert(data);
        }
    });
});

This will give Your error messages in a alert window and Your site won't reload if I'm not mistaken. 这将在警报窗口中显示您的错误消息,如果我没有记错,您的网站将不会重新加载。

There are many ways of doing this so this is a opinion based question which will get you several ways of accomplishing this. 有很多方法可以做到这一点,所以这是一个基于意见的问题,它将为您提供几种方法来实现这一目标。

You could do an ajax request to submit the data that way no reloading of the page and on the success of the call if any errors are in the response show the errors near the input that caused the error. 如果响应中的任何错误显示导致错误的输入附近的错误,您可以执行ajax请求以提交不重新加载页面的数据和调用成功。 This would require the use of javascript and setting a hidden element to the error and displaying it or generating the element containing the error and appending it to the DOM. 这将需要使用javascript并为错误设置隐藏元素并显示它或生成包含错误的元素并将其附加到DOM。

do as Amal Murali shows and put the html and validation script in the same script file and output the errors right away, or even better echo the errors near the inputs that caused them 像Amal Murali一样显示并将html和验证脚本放在同一个脚本文件中并立即输出错误,甚至更好地回应导致它们的输入附近的错误

yet another way would be to have contact.php do the validation and then on invalid data print out contact.html and again put the errors near the inputs. 另一种方法是让contact.php进行验证然后在无效数据上打印出contact.html并再次将错误放在输入附近。

    <?php
    // define variables and set to empty values
    $firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr = "";
    $firstname = $lastname = $username = $password = $gender = $comments = "";
    $course = array();
    //var_dump($_POST['gender']);
    //exit;
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $variables = array();
    $variables = initialize();
    $errors = array();
    $errors = validate_errors($variables);

    if (count($errors) == 0) {
        //database operation
        //exit;
    }
    }  
    function clean($data) {
    $data = strip_tags(htmlspecialchars(stripslashes(trim($data)))); 
     //trim :- Strip whitespace (or other characters) from the beginning and end of a string
     //The stripslashes() function removes backslashes.Prevents XSS
     //htmlspecialchars :- Converts the predefined characters "<" (less than) and ">" (greater than) to HTML entities:< (less than) becomes &lt; and > (greater than) becomes &gt;Helps in preventing XSS
     //The strip_tags() function strips a string from HTML, XML, and PHP tags.
    return $data;
    }

    function initialize(){
    $var = array();
    $var['firstname'] = clean($_POST['firstname']);
    $var['lastname'] = clean($_POST['lastname']);
    $var['username'] = clean($_POST['username']);
    $var['password'] = clean($_POST['password']);
    if(!empty($_POST['gender'])) {                //if-else condition is used because here we don't type in any data,but just select data
    $var['gender'] = $_POST['gender'];
    }  else {
        $var['gender'] = '';
    }
    //var_dump($_POST[gender]);
    if(!empty($_POST['course'])) {               //if-else condition is used because here we don't type in any data,but just select data
    $var['course'] = $_POST['course'];
    } else {
        $var['course'] = '';
    }
    $var['comments'] = clean($_POST['comments']);
    return $var;
     }

    function validate_errors($var) {    //is an array being passed into this function??have a look at arg of validateFirstName.
    $errors = array();

    $errors['firstname'] = validateFirstName($var['firstname']);//should return error string or ''
    $errors['lastname'] = validateLastname($var['lastname']);
    $errors['username'] = validateUserName($var['username']);
    $errors['password'] = validatePassword($var['password']);
    $errors['gender'] = validateGender($var['gender']);
    $errors['course'] = validateCourse($var['course']);
    $errors['comments'] = validateComments($var['comments']);
    return $errors;
   }

      function validateFirstName($fname){

      if(empty($fname)){
        global $firstnameErr;
        $firstnameErr = "First name is required";
        return $firstnameErr;
    } else if (!preg_match("/^[a-zA-Z ]*$/", $fname)){ // check if name only contains letters and whitespace.Performs a regular expression match
        global $firstnameErr;
        $firstnameErr = "Only letters are allowed";
        return $firstnameErr;
    } else {
        global $firstname;
       $firstname = $fname;
       return ''; 
    }   
}    

function validateLastName($lname){

    if(empty($lname)){
        return '';
    } else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
        global $lastnameErr;
        $lastnameErr = "Only letters are allowed";
         return $lastnameErr;
    } else {
        global $lastname;
        $lastname = $lname;
       return ''; 
    }
}

function validateUserName($uname) {

    if(empty($uname)) {
        global $usernameErr;
        $usernameErr = "Username is required";
        return $usernameErr;
    } else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)){ // checks if username contains only letters and digits
        global $usernameErr;
        $usernameErr = "Only letters and digits are allowed";
        return $usernameErr;
    } else {
        global $username;
        $username = $uname;
       return ''; 
    }  
}

function validatePassword($pword){

    if(empty($pword)) {
        global $passwordErr;
        $passwordErr = "Password is required";
        return $passwordErr;
    } else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword) === 0) {
        global $passwordErr;
        $passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
        return $passwordErr;
    } else {
        global $password;
        $password = $pword;
       return '';  
    }
}    

function validateGender($gen){

    if(empty($gen)) {
        global $genderErr;
        $genderErr = "Gender is required";  
      return $genderErr;
    } else {
        global $gender;
        $gender = $gen;
        return '';
    }
}

function validateCourse($cour){

    if(empty($cour)) {
        global $courseErr;
        $courseErr = "Select atleast one";
        return $courseErr;
    } else {
        global $course;
        $course = $cour;
        return '';
    }
}

function validateComments($comm){

    if(empty($comm)) {
        return '';
    } else {
        global $comments;
        $comments = $comm;
        return '';
    }
}


    //renderform();



    ?>


    <html>
    <head>
        <title>Sample Form</title>
        <style>
            .error {color: #FF0000;}
        </style>
    </head>
    <body>
        <p><span class="error">* required field.</span></p>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
            <label for="firstname">Firstname:</label>
            <input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" /><span class="error">* <?php echo $firstnameErr; ?></span><br/><br/>
            <label for="lastname">Lastname:</label>
            <input type="text" name="lastname" id="lastname" value="<?php echo $lastname; ?>" /><span class="error"> <?php echo $lastnameErr; ?></span><br/><br/>
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" value="<?php echo $username; ?>" /><span class="error">* <?php echo $usernameErr; ?></span><br/><br/>
            <label for="password">Password:</label>
            <input type="password" name="password" id="password" /><span class="error">* <?php echo $passwordErr; ?></span><br/><br/>
            Gender:
            <label for="male">Male</label>
            <input type="radio" name="gender" id="male" <?php if (isset($gender) && $gender == "male") echo "checked"; ?> value="male" />  
            <label for="female">Female</label>
            <input type="radio" name="gender" id="female" <?php if (isset($gender) && $gender == "female") echo "checked"; ?> value="female" /><span class="error">* <?php echo $genderErr; ?></span><br/><br/>
            <label for="course">Course:</label>
            PHP<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("PHP",$_POST["course"]))){echo "checked";}?> value="PHP" />
            HTML<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("HTML",$_POST["course"]))){echo "checked";}?> value="HTML" />
            CSS<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("CSS",$_POST["course"]))){echo "checked";}?> value="CSS" />
            Javascript<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("Javascript",$_POST["course"]))){echo "checked";}?> value="Javascript" /><span class="error">* <?php echo $courseErr; ?></span><br/><br/>
            <label for="comments">Comments:</label><br/>
            <textarea name="comments" rows="4" cols="20" id="comments"/><?php echo $comments; ?></textarea><br/><br/>
        <input type = "submit" value="Submit" name="submit">
    </form>
     <?php
    echo "<h2>Your Input:</h2>";
    echo "Firstname:" . $firstname;
    echo "<br>";
    echo "Lastname:" . $lastname;
    echo '<br>';
    echo "Username:" . $username;
    echo '<br>';
    echo "Password:" . $password;
    echo '<br>';
    echo "Gender:" . $gender;
    echo '<br>';
    global $string;
    $string = implode(",",$course);
    echo "Course(/s):" . $string;
    echo '<br>';
    echo "Comments:" . $comments;
    echo '<br>';
    ?>
    </body>
    </html>

code of index.php(This file is run first) index.php的代码(此文件先运行)

<?php
define('PROJECT',$_SERVER['DOCUMENT_ROOT'].'PhpSample');
include (PROJECT.'/utilities.php');
include ('constant.php');

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

$errors = validate_errors($variables);
$counter = 0;
foreach ($errors as $value) {
    if ($value === '') {
        $counter++;
    }
}

//if there are no errors
if ($counter == 7) {
    //database operation
    $con = mysqli_connect($host, $user, $pword);
    if (!$con) {
        echo 'Error connecting to database. Please try again later';
        exit;
    }
    $val = cleanandinsert($variables,$con,$dbname);
    mysqli_close($con);
    if(!$val){
        echo 'Could not register. Please try again later';
        exit;
    }
    header("Location:http://localhost/PhpSample/target.php?vals=" .     urlencode(serialize($variables))); 
    exit;
  }
}


include('myform.phtml');
?>

Code of target.php target.php的代码

<?php
include 'process.php';
$Values= unserialize(urldecode($_GET['vals'])); 
echo "<h2>Your Input:</h2>";
echo "Firstname:".$Values['firstname'];
echo "<br>";
echo "Lastname:".$Values['lastname'] ;
echo '<br>';
echo "Username:".$Values['username'] ;
echo '<br>';
echo "Password:".$Values['password'] ; 
echo '<br>';
echo "Gender:".$Values['gender'] ;
echo '<br>';
if (!empty($Values['course'])) {
    $string = implode(',', $Values['course']);
} else {
    $string = "";
}
echo "Course(/s):" . $string;
echo '<br>';
echo "Comments:".$Values['comments'] ; 
echo '<br>';
?>

Code of constant.php constant.php的代码

<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr     = "";
$firstname = $lastname = $username = $password = $gender = $comments = "";
$course = array();
$variables = initialize();
$host = 'localhost';
$user = 'root';
$pword = '';
$dbname = 'mydb';
$tablename = 'userdata';
?>

Code of myform.phtml 代码myform.phtml

<html>
<head>
    <title>Sample Form</title>
    <style>
        .error {color: #FF0000;}
    </style>
</head>
<body>
    <p><span class="error">* required field.</span></p>
    <form method="post" action="./index.php"> 
        <label for="firstname">Firstname:</label>                                                           
        <input type="text" name="firstname" id="firstname" value="<?php if (isset($variables['firstname']) ? print_r($variables['firstname']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['firstname']) ? print_r($errors['firstname']) : '') ; ?></span><br/><br/>
        <label for="lastname">Lastname:</label>
        <input type="text" name="lastname" id="lastname" value="<?php if (isset($variables['lastname']) ? print_r($variables['lastname']) : '') ; ?>" /><span class="error"> <?php if (isset($errors['lastname']) ? print_r($errors['lastname']) : '') ; ?></span><br/><br/>
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" value="<?php if (isset($variables['username']) ? print_r($variables['username']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['username']) ? print_r($errors['username']) : '') ; ?></span><br/><br/>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" /><span class="error">* <?php if (isset($errors['password']) ? print_r($errors['password']) : '') ; ?></span><br/><br/>
        Gender:
        <label for="male">Male</label>
        <input type="radio" name="gender" id="male" <?php if (isset($variables['gender']) && ($variables['gender'] == "male")) echo "checked"; ?> value="male" />  
        <label for="female">Female</label>
        <input type="radio" name="gender" id="female" <?php if (isset($variables['gender']) && ($variables['gender'] == "female")) echo "checked"; ?> value="female" /><span class="error">* <?php if (isset($errors['gender']) ? print_r($errors['gender']) : '') ; ?></span><br/><br/>
        <label for="course">Course:</label>
        PHP<input type="checkbox" name="course[]" id="course" <?php echo getChecked("PHP") ?>  value="PHP" />
        HTML<input type="checkbox" name="course[]" id="course" <?php echo getChecked("HTML") ?> value="HTML" />
        CSS<input type="checkbox" name="course[]" id="course" <?php echo getChecked("CSS") ?> value="CSS" />
        Javascript<input type="checkbox" name="course[]" id="course" <?php echo getChecked("Javascript") ?> value="Javascript" /><span class="error">* <?php if (isset($errors['course']) ? print_r($errors['course']) : '') ; ?></span><br/><br/>
        <label for="comments">Comments:</label><br/>
        <textarea name="comments" rows="4" cols="20" id="comments"/><?php if (isset($variables['comments']) ? print_r($variables['comments']) : '') ; ?></textarea><br/><br/>
    <input type = "submit" value="Submit" name="submit">
</form>

Code of utilities.php utilities.php代码

<?php

/** * It cleans the variable and returns variable free from cross site cripting. / ** *它清除变量并从交叉站点cripting返回变量。 * @return variable free from whitespaces,stripped of slashes,tags. * @return变量没有空白,删除斜杠,标签。 */ * /

function clean($data, $ishtmltype = FALSE) {
if ($ishtmltype) {  //for database operation
    $data = htmlspecialchars(stripslashes(trim($data)));
    return $data;
}
$data = strip_tags(htmlspecialchars(stripslashes(trim($data))));

return $data;
}

/** * It returns an array of variables which are cleansed with the help of "clean()" * @return $var array */ / ** *它返回一个变量数组,这些变量在“clean()”* @return $ var array * /的帮助下被清理

  function initialize() {
   $var = array();
   $var['firstname'] = isset($_POST['firstname']) ? clean($_POST['firstname']) : '';
   $var['lastname'] = isset($_POST['lastname']) ? clean($_POST['lastname']) : '';
   $var['username'] = isset($_POST['username']) ? clean($_POST['username']) : '';
   $var['password'] = isset($_POST['password']) ? $_POST['password'] : '';
   if (!empty($_POST['gender'])) {                
    $var['gender'] = $_POST['gender'];
   } else {
    $var['gender'] = '';
  }
  //var_dump($_POST[gender]);
   if (!empty($_POST['course'])) {               
    $var['course'] = $_POST['course'];
   } else {
    $var['course'] = '';
   }
   $var['comments'] = isset($_POST['comments']) ? clean($_POST['comments']) : '';
    return $var;
   }

/** * It returns an array of error variables which have error messages in them * @param type $var array * @return $errors array */ / ** *它返回一个错误变量数组,其中包含错误消息* @param type $ var array * @return $ errors array * /

function validate_errors($var) {    
$errors = array();

$errors['firstname'] = validateFirstName($var['firstname']); //should return error   string or ''
$errors['lastname'] = validateLastname($var['lastname']);
$errors['username'] = validateUserName($var['username']);
$errors['password'] = validatePassword($var['password']);
$errors['gender'] = validateGender($var['gender']);
$errors['course'] = validateCourse($var['course']);
$errors['comments'] = validateComments($var['comments']);
return $errors;
}

/** * It returns an error message, if any, in the first name * @param type $fname * @return string or null if not found */ / ** *它返回第一个名称中的错误消息(如果有)* @param类型$ fname * @return字符串或如果未找到则返回null * /

function validateFirstName($fname) {

if (empty($fname)) {
    $firstnameErr = "First name is required";
    return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z']*$/", $fname)) { // check if name only contains   letters and whitespace.Performs a regular expression match
    $firstnameErr = "Only letters are allowed";
    return $firstnameErr;
}
  else if (strlen($fname) < 3){
    $firstnameErr = "Atleast 3 characters";
    return $firstnameErr;
  }
   else if (strlen($fname) > 60){
    $firstnameErr = "Not more than 60 characters";
    return $firstnameErr;
  }
return '';
}

/** * It returns an error message, if any, in the last name * @param type $lname * @return string or null if not found */ / ** *它返回一个错误消息,如果有的话,在姓氏中* @param类型$ lname * @return字符串或null如果没有找到* /

function validateLastName($lname) {

if (empty($lname)) {
    return '';
} else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
    $lastnameErr = "Only letters are allowed";
    return $lastnameErr;
}
else if (strlen($lname) > 60){
    $firstnameErr = "Not more than 60 characters";
    return $firstnameErr;
  }
return '';
}

/** * It returns an error message, if any, in the user name * @param type $uname * @return string or null if not found */ / ** *它在用户名中返回错误消息(如果有)* @param type $ uname * @return string或null if null found * /

function validateUserName($uname) {

if (empty($uname)) {
    $usernameErr = "Username is required";
    return $usernameErr;
} else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)) { // checks if username contains only letters and digits
    $usernameErr = "Only letters and digits are allowed";
    return $usernameErr;
}
else if (strlen($uname) < 3){
    $firstnameErr = "Atleast 3 characters";
    return $firstnameErr;
  }
   else if (strlen($uname) > 60){
    $firstnameErr = "Not more than 60 characters";
    return $firstnameErr;
  }
  return '';
}     

/** * It returns an error message, if any, in the password * @param type $pword * @return string or null if not found */ / ** *它在密码* @param类型$ pword * @return字符串中返回错误消息(如果有)或如果未找到则返回null * /

function validatePassword($pword) {

if (empty($pword)) {
    $passwordErr = "Password is required";
    return $passwordErr;
} else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword)     === 0) {
    $passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
    return $passwordErr;
}
return '';
}

/** * It returns an error message, if any, in the gender * @param type $gen * @return string or null if not found */ / ** *它会在性别* @param类型$ gen * @return字符串中返回错误消息(如果有),如果找不到则返回null * /

function validateGender($gen) {

if (empty($gen)) {
    $genderErr = "Gender is required";
    return $genderErr;
} else if (($gen != "male") && ($gen != "female")) {
    $genderErr = "Not a valid selection";
    return $genderErr;
}
return '';

} }

/** * It returns an error message, if any, in the course * @param type $cour * @return string or null if not found */ / ** *它会在* @param类型$ cour * @return字符串中返回错误消息(如果有)或者如果找不到则返回null * /

function validateCourse($cour) {

if (empty($cour)) {
    $courseErr = "Select atleast one";
    return $courseErr;
} else if (array_values($cour) != ("PHP" && "HTML" && "CSS" && "Javascript")) {
    $courseErr = "Not a valid selection";
    return $courseErr;
}
return '';
}

/** * It doesnot return an error message, but accepts any content * @param type $comm * @return null */ / ** *它不会返回错误消息,但接受任何内容* @param类型$ comm * @return null * /

function validateComments($comm) {

if (empty($comm)) {
    return '';
}
return '';
}

/** * It removes any special characters in a string and inserts the validated user data into the database * @param type $variables array * @param type $con * @param type $dbname * @return boolean */ / ** *它删除字符串中的任何特殊字符并将经过验证的用户数据插入数据库* @param类型$ variables数组* @param类型$ con * @param类型$ dbname * @return boolean * /

function cleanandinsert($variables, $con, $dbname) {

$firstname = mysqli_real_escape_string($con, $variables['firstname']); //The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.
$lastname = mysqli_real_escape_string($con, $variables['lastname']);
$username = mysqli_real_escape_string($con, $variables['username']);
$password = sha1($variables['password']);    
$gender = mysqli_real_escape_string($con, $variables['gender']);
$string = implode(',', ($variables['course']));
$course = mysqli_real_escape_string($con, $string);
$comments = mysqli_real_escape_string($con, $variables['comments']);
$sql = "INSERT INTO $dbname.userdata (firstname,lastname,username,password,gender,course,comments)
                VALUES ('$firstname','$lastname','$username','$password','$gender','$course','$comments')";

if (!mysqli_query($con, $sql)) {

        return FALSE;        
}
return TRUE;
}

/** * It checks the checked checkboxes on the submission of the wrong data ie it remembers the checked checkbox. / ** *它会检查提交错误数据时选中的复选框,即它会记住选中的复选框。 * @param type $course * @return checked checkbox or null if a checkbox is not checked */ * @param type $ course * @return checked复选框,如果未选中复选框则为null * /

function getChecked($course){
if(!empty($_POST['course']) && in_array($course, $_POST["course"])){
    return 'checked';
}
return '';
}

?>

你可以在if()使用梯形if..else结构if()你将你的条件和条件为false它将转到错误信息,然后你可以把主窗体的链接,以便用户可以回去...

有很多方法可以做到这一点,但是这样做的简单方法是“将你的整个表单代码放在php文件中,只创建一个文件,我不确定它应该有效,错误将显示在表单的下方首先写你的表单代码,然后写你的PHP脚本“。:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM