doulao1934
doulao1934
2014-12-06 18:01
浏览 68

PHP验证表单

I have been trying to get validation messages from my login.php to display on the page with the form, where am I going wrong? I did try JavaScript at one point to display the information with no luck, it keeps displaying as seen in the image below.

I know it could be added to the same page for the result I want but I'm trying to do it as a clean page, with no jQuery, some vanilla JavaScript at very most. The aim is to have the validation messages above the form, at first I was thinking spans but I'm not sure where to look for tutorials on how to output results from another file while staying on the same page.

http://snag.gy/SI9lq.jpg

      <table border ='0'>
                <form action="login.php"  method="POST">
                    <tr><td>Username:</td> <td><input type="text" name="username" required></td></tr>
                    <tr><td>Password:</td> <td><input type="password" name="password" required></td><tr>
                    <tr><td><input button id="myBtn" type="submit" value="Log in"><td></tr>
                    <tr><td><a href='register.php'>Register</a></td></tr>
            </table> 




     <?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$errors = array();


if ($username&&$password)
{

$connect = mysql_connect("localhost","root","") or die ("Could not connect");
mysql_select_db ("login") or die ("Could not find database");

$query = mysql_query("SELECT * FROM users WHERE username ='$username'");

$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
    while ($row =mysql_fetch_assoc($query))
    {
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    }

    if ($username==$dbusername&&$password==$dbpassword)
    {
        echo header( 'Location: member.php' ) ;
        $_SESSION['username']=$dbusername;
    }
    else 
        echo"
         <script type=\"text/javascript\">
        window.onload = function latestNews(){
      var newPara = document.createElement('p');
      var add_news = document.createTextNode('Incorrect password');
      newPara.appendChild(add_news);
      var getSecond = document.getElementById('footer');
      document.body.insertBefore(newPara, getSecond);
    };
         </script>
    ";
}
else
    die("That user dosen't exist");

}

else
    die("Please enter a username and a password");
?>

EDIT

I attempted to add JavaScript although it had the same effect.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • douban5644
    douban5644 2014-12-07 22:16
    已采纳

    Well it's not excalty what I wanted but I forced myself to learn Ajax login, it's not the best it the world, well it's my first ajax login but for anyone who is interested in the answer:

    Save as login:
        <?php session_start(); $username=$ _POST[ 'username']; $password=$ _POST[ 'password']; $errors=a rray(); if ($username&&$password) { $connect=m ysql_connect( "localhost", "root", "") or die ( "Could not connect"); mysql_select_db ( "login") or die ( "Could not find database"); $query=m ysql_query( "SELECT * FROM users WHERE username ='$username'"); $numrows=m ysql_num_rows($query); if ($numrows !=0) { while ($row=mysql_fetch_assoc($query)) { $dbusername=$ row[ 'username']; $dbpassword=$ row[ 'password']; } if ($username==$dbusername&&$password==$dbpassword) { echo header( 'Location: member.php' ) ; $_SESSION[ 'username']=$dbusername; } else echo "Incorrect password"; } else die( "That user dosen't exist"); } else die( "Please enter a username and a password"); ?>
    
    Save as scripts.js:
    
    
        function createXMLHttpRequestObject() 
        {
          var ajaxObject = false;
          if (window.XMLHttpRequest) 
          {
            ajaxObject = new XMLHttpRequest();
          } 
          else if (window.ActiveXObject) 
          {
                try 
                {
                    ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
             } 
        catch(e) 
                 {
                    try 
                        {
                        ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
                    } 
        catch(e) 
                        {
                            ajaxObject = false;
                     }
             }
          }
          return ajaxObject;
        }
    
        function grabFile(file) 
        {
          var isAjax = createXMLHttpRequestObject();
          if (isAjax) 
            {
            isAjax.onreadystatechange = function() 
              {
              getCurrentState(isAjax);
              };
            isAjax.open("GET", file, true);
            isAjax.send(null);
          }
        }
    
        function getCurrentState(thisFile) 
        {
          if (thisFile.readyState == 4) 
          {
            if (thisFile.status == 200 || thisFile.status == 304) 
            {
              document.getElementById('myBtn').innerHTML = 
              thisFile.responseText;
            }
          }
        }
    
    
        function ajax_post(){
            // Create our XMLHttpRequest object
            var hr = new XMLHttpRequest();
            // Create some variables we need to send to our PHP file
            var url = "login.php";
            var un = document.getElementById("username").value;
            var pw = document.getElementById("password").value;
            var vars = "username="+un+"&password="+pw;
            hr.open("POST", url, true);
            // Set content type header information for sending url encoded variables in the request
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // Access the onreadystatechange event for the XMLHttpRequest object
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var return_data = hr.responseText;
                    document.getElementById("status").innerHTML = return_data;
                }
            }
            // Send the data to PHP now... and wait for response to update the status div
            hr.send(vars); // Actually execute the request
            document.getElementById("status").innerHTML = "processing...";
        }
    

    I didn't include the database it was starting to become a wall of text. Thank you to everyone for the advice and suggestions.

    点赞 评论
  • doulin2947
    doulin2947 2014-12-06 18:12

    what about if you do this

    <?php
    $connect = mysql_connect("localhost","root","") or die ("Could not connect");
    mysql_select_db ("login") or die ("Could not find database");
    
    session_start();
    function output_errors($errors){
    return '<ul class="a"><li><strong>'.implode('</li><li>', $errors) .'</strong></li></ul>';
    }
    
    $errors = array();
    
    if(empty($_POST) === false) {
    $required_fields = array('username', 'password');
    foreach ($_POST as $key=>$value) {
    if(empty($value) && in_array($key, $required_fields) === true){
    $errors[] = 'user name and password is empty !';
    break 1;
    }
    }
    $username = $_POST['username'];
    $password = $_POST['password'];
    if(strlen($_POST['password']) < 5){
    $errors[] = 'Your password must be at least 5 Characters.';
    }
    if ($username&&$password)
    {
    
    $query = mysql_query("SELECT * FROM users WHERE username ='$username'");
    
    $numrows = mysql_num_rows($query);
    if ($numrows !=0)
    {
        while ($row =mysql_fetch_assoc($query))
        {
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        }
    
        if ($dbusername&&$password != $dbpassword) {
         $errors[] = "password wrong";  
        }
    }
    }
    }
    if(empty($_POST) === false && empty($errors) === true && $username==$dbusername&&$password==$dbpassword){
    echo header( 'Location: member.php' ) ;
    $_SESSION['username']=$dbusername;
    exit();
    }else if(empty($errors) === false){
    echo output_errors($errors);
    }
    ?>
    
                  <table border ='0'>
                            <form action="login.php"  method="POST">
                                <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><input button id="myBtn" type="submit" value="Log in"><td></tr>
                                <tr><td><a href='register.php'>Register</a></td></tr>
                        </table> 
    
    点赞 评论
  • dongqing6755
    dongqing6755 2014-12-06 18:47

    To display a simple error message you simply echo it above the form. See if this works

    <?php
    
    session_start();
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    $errors   = array();
    $msg      = ""; //define an error msg variable
    
    
    if (isset($_POST['username'], $_POST['password'])) {
    
        $connect = mysql_connect("localhost", "root", "") or die("Could not connect");
        mysql_select_db("login") or die("Could not find database");
    
        $query = mysql_query("SELECT * FROM users WHERE username ='$username'");
    
        $numrows = mysql_num_rows($query);
        if ($numrows != 0) {
            while ($row = mysql_fetch_assoc($query)) {
                $dbusername = $row['username'];
                $dbpassword = $row['password'];
            }
    
            if ($username == $dbusername && $password == $dbpassword) {
                echo header('Location: member.php');
                $_SESSION['username'] = $dbusername;
                $_SESSION['userid']   = $userid;
            } else
                $msg = "Incorrect password";
        } else
            $msg = "That user dosen't exist";
    
    }
    
    else
        $msg = "Please enter a username and a password";
    
    ?>
    
    
    <div class='errorMsg'><?php echo $msg; ?></div>
      <form action="login.php" method="post"></form>
      <table border='0'>
        <tr>
          <td>Username:</td>
          <td><input name="username" required="" type="text"></td>
        </tr>
    
        <tr>
          <td>Password:</td>
          <td><input name="password" required="" type="password"></td>
        </tr>
        <tr>
          <td></td>
        </tr>
        <tr>
          <td><input id="myBtn" type="submit" value="Log in"></td>
          <td></td>
        </tr>
        <tr>
          <td>
            <a href='register.php'>Register</a>
          </td>
        </tr>
      </table>
      </form>
    
    点赞 评论
  • duanhuang4306
    duanhuang4306 2014-12-06 18:48

    Write a new PHP program, perhaps called checker.php. It is the job of checker.php to check for errors and present a "success" page if none are found. However, if checker.php finds an error, it sets a PHP variable, $error = TRUE; (You could use an array of you want to be able to report more than one error type; just have each element of the array be a code/abbreviation for the error type.) If there is an error, checker.php issues include 'login.php' which will redisplay your login page.

    Here's the trick: have login.php check for $error like this: if isset($error) { ... and if so, use PHP's echo to display your error messages. You can carry forward things like the user ID and password in a $error array if you like. (But heed the cautions about security in the comments.)

    If $error is not set, your login page is being displayed for the first time. Display it without error messages.

    Here is a sort-of minimalist login.php:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Login Form</title>
    <style type="text/css">
    p.error {color: red;}
    </style>
    </head>
    <body>
    <?php
       if (isset($error)) {  // same message for user ID or password for security
          echo '<p class="error">Error in user ID or password; please re-enter.</p>';
       }
    ?>
    <form method="post" action="checker.php">
    <label>User ID: <input type="text" name="userid" /></label><br />
    <label>Password: <input type="text" name="password" /></label><br />
    User ID: <input type="submit" value="Login" /><br />
    </form>
    </body>
    </html>
    

    And here is checker.php:

    <?php
        $userid=(isset($_POST['userid']) ? $_POST['userid'] : FALSE);
        $password=(isset($_POST['password']) ? $_POST['password'] : FALSE);
        if ($userid !== 'jsnow') $error[] = 'userid';
        if ($password !== 'Ygritte') $error[] = 'password';
        if (isset($error)) {
            include 'login.php';
            exit;
        }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Login Success</title>
    </head>
    <body>
    <h1>Success!</h1>
    <p>You're logged in.  What do you want to do?</p>
    </body>
    </html>
    

    It is possible to include the code from checker.php` in the login.php page, but it's easier to see what's going on if you write two separate pages. Try that before you try combining them.

    点赞 评论

相关推荐