doushang7209
doushang7209
2014-04-27 19:23

PHP在同一页面上提交表单,回显如下表所示

已采纳

I'm aware that this question has been asked a huge number of times but the answers seem really specific to the script posted and with my current knowledge I can't make the transition from the corrected script to implementing it into my own.

This all works fine - it submits on the same page and provides feedback of any errors, but I want any errors to be echoed beneath the form making it more convenient for the user to just change what they entered incorrectly and re-submit.

From what I can gather from the questions I read before posting this - it may only be possible using jQuery/Ajax?

My script:

<?php

if(isset($_POST['submit'])){
require "connection.php";

$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$repeat_password = $_POST["repeat_password"];

$username_query = mysql_query("SELECT id FROM users WHERE username = '$username'");
$email_query = mysql_query("SELECT id FROM users WHERE email = '$email'");

if($username == "" || $password == "" || $repeat_password == "" || $email == ""){
  die("All boxes must be filled out!");
}// ^ Checking if all boxes have been filled out
else {
    if (!ctype_alnum($username)){
        die("Username can only contain letters and numbers");
    }// ^ Checking if username is alphanumeric
    else {
        if (strlen($username) < 6 || strlen($username) > 15){
            die("Username must be between 6-15 characters.");
        }// ^ Checking if username is between 6-15 characters
        else {
            if (mysql_num_rows($username_query) != 0){
                die("Username is taken, please choose another.");
            }// ^ Checking if username exists in database
            else {
                if (!preg_match("/[0-9]/",$password)){
                    echo "password doesnt contain a number";
                    }
                else {
                    if ($password != $repeat_password){
                        die("Passwords do not match");
                    }// ^ Checking if password and repeat_password match
                    else {
                        if (strlen($password) < 6){
                            die("Password must be atleast 6 characters long.");
                        }// ^ Checking if password is longer than 6 characters
                        else {
                            if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
                                die("E-mail address is not vaild.");
                            }// ^ Checking if e-mail address is valid
                            else {
                                if (mysql_num_rows($email_query) != 0){
                                    die("This e-mail address has already been used to create a different account.");
                                }// ^ Checking if e-mail address has already been used
                                else {
                                    mysql_query("INSERT INTO users (username, password, email, signup_date) VALUES ('$username', '$password', '$email', CURDATE())") or die(mysql_error());
                                    echo "Account succesfully created, welcome ".$username."!";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
}
exit;
}

// 

?>

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <table>
                <tr>
                    <td>
                        Username:
                    </td>
                    <td>
                        <input type="text" name="username">
                    </td>
                </tr>
                <tr>
                    <td>
                        Password:
                    </td>
                    <td>
                        <input type="password" name="password">
                    </td>
                </tr>
                <tr>
                    <td>
                        Repeat password:
                    </td>
                    <td>
                        <input type="password" name="repeat_password">
                    </td>
                </tr>
                <tr>
                    <td>
                        E-mail:
                    </td>
                    <td>
                        <input type="email" name="email">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <center><input type="submit" name="submit"></center>
                    </td>
                </tr>
            </table>
        </form>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongxieyou3314 dongxieyou3314 7年前

    Answer: Yes, you have to use jQuery there.

    You can validate form just after user entered 1st letter. You can validate on key up/down or on submit. I suggest to use jQuery Validation Plugin.

    To sumbit form use ajax requests. It is rly simple. You can read about it here. There are some examples at the end page I had given.

    Note, that if you will use jQuery Validation Plugin you can send ajax request on valid action. Using this, ajax request with serialized form will be sent on form submit + on form valid. If form has some invalid fields, errors will be shown, if there are no errors, ajax-request will be send.

    Advice: Your arhitecture not very good. Why? If people will write bad name and make 10 more other errors, only 1 error:

    Username can only contain letters and numbers

    will be shown. Why? Because of you arhitecture. After that he will correct 2nd erorr. 3rd error etc.

    I suggest you do to handle errors this way:

    $errors = array();
    $errorsFlag = false;
    
    if(check_username1()) {
        $errors[] = 'Tell about this error';
        $errorsFlag = true;
    }
    
    if(check_username2()) {
        $errors[] = 'Tell about this error';
        $errorsFlag = true;
    }
    if(check_mail()) {
        $errors[] = 'Tell about this error';
        $errorsFlag = true;
    }
    

    And how to output it? Use this:

    if($errorsFlag == true) {
        foreach($errors as $error) {
            echo $error . " <br /> ";;
        }    
    }
    
    点赞 评论 复制链接分享
  • dsbiw2911188 dsbiw2911188 7年前

    yes, you'll need javascript. but not necessarily jQuery or ajax.

    but php without the use of ajax always needs you to reload the page cause otherwise the php-code will not be executed.

    search for some kind of javascript/jQuery validation scripts if you don't want the page to be reloaded. otherwise (if you don't care about page-reloading), you can put out your error message at the end of the form with php as well.

    点赞 评论 复制链接分享
  • dongxiaoyan4388 dongxiaoyan4388 7年前

    I always set my errors as a session. This allows you to set multiple errors at once, and print them wherever you want.

    The following if statements are just examples of where you would set the errors...

    session_start(); //you will need this
    
    if ( username_exists($un) ) {
    
        handleError("Username already exists!");
    
    }
    

    ...

    if ( !passwordIsStrong($pw) ) {
    
        handleError("Password is not strong enough!");
    
    }
    

    Here's the functions that actually set/print the errors.

    function handleError( $err ) {
    
        //get any existing errors
        $existing = isset($_SESSION['form-errors']) ? $_SESSION['form-errors'] : '';
    
        //append the new error to the existing ones. Over-write the session with new data.
        $_SESSION['form-errors'] = "$existing<li>$err</li>";
    
    }
    
    function getErrors() {
    
        if( isset($_SESSION['form-errors']) )
    
             echo $_SESSION['form-errors'];
    
    
    }
    

    getErrors(); can be called anywhere in your html. It will print something like this...

    <li>Username already exists!</li> <li>Password is not strong enough!</li>

    It's kind of like a log. But it's worked for me on all of my projects!

    点赞 评论 复制链接分享