2014-03-02 102 views
0

我試圖在同一頁面上顯示錯誤消息。我知道我必須使用JavaScript。這是我的代碼到目前爲止。然而它後面說1。我thnk這是從我的numrows!== 0我將如何擺脫這1. 1.登錄同一頁面時顯示錯誤消息

<?php 
session_start(); 
$username = $_POST['username']; 
$password = $_POST['password']; 

if ($username&&$password) 
{ 
    $host_name = 'localhost'; 
$db_user ='root'; 
$db_pass = ''; 
$db_name = 'login'; 
/* Connect to MySQL */ 
$con = mysql_connect("$host_name","$db_user","$db_pass") or die ("Couldn't connect!"); 
$db = mysql_select_db("$db_name") or die ("Couldn't connect to 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']; 

    } 
    /*Check to see if they match! */ 
    if ($username==$dbusername&&$password==$dbpassword) 
    { 
     echo "You're in! <a href='member.php'> Click</a> here to enter the member page"; 
      $_SESSION['username']==$username; 
    } 
    else 
     echo "Incorrect password"; 
    } 
    else 
     die("That user doesn't exist!"); 

    echo $numrows; 
} 
else 
    die("Please enter username and/or password!"); 

?> 
+1

你的代碼很容易被mysql注入 – Fabio

+1

只要刪除echo $ numrows; –

+0

好的,謝謝,請指教在java – user3369387

回答

2

你真的不需要JavaScript來做到這一點。你可以在PHP中完成。如下所示。

我修改了你的PHP代碼。將其放置在您執行登錄的文件中。

<?php 

    session_start(); 
    $username = $_POST['username']; 
    $password = $_POST['password']; 

    if (!empty($username) && !empty($password)) 
    { 
     $host_name = 'localhost'; 
     $db_user ='root'; 
     $db_pass = ''; 
     $db_name = 'login'; 

     $con = mysql_connect($host_name, $db_user, $db_pass) or die ("Couldn't connect!"); 
     $db = mysql_select_db($db_name) or die ("Couldn't connect to database!"); 

     $query = mysql_query("SELECT * FROM users WHERE username=".mysql_real_escape_string($username)." and password = ".mysql_real_escape_string($password)); 
     $numrows = mysql_num_rows($query); 

     if($numrows == 1) 
     { 
      $_SESSION['username'] = $username; //Store username to session for futher authorization 
      header("Location: member.php"); //Redirect user to home page 
     } 
     else { 
       $_SESSION['errMsg'] = "Invalid username or password"; 
     } 
     header("Location: login.php"); //Redirect user back to your login form 
    } 
    else { 
     die("Please enter username and/or password!"); 
     } 

    ?> 

只需在登錄表單上做這樣的事情。

<?php session_start(); ?> 
    <html> 
    <body> 
     <div id="errMsg"> 
      <?php if(!empty($_SESSION['errMsg'])) { echo $_SESSION['errMsg']; } ?> 
     </div> 
     <?php unset($_SESSION['errMsg']); ?> 
    </body> 
+0

我做了以下更改,但它仍然導致其他頁面的密碼不正確,但在其上我得到未定義的用戶名和密碼索引:我不斷收到這個時,我包括會話開始,當我刪除它我沒有得到這些錯誤,我也注意到,當我點擊後退按鈕時,它有時會在我的登錄表單上方顯示無效的用戶名和密碼。 – user3369387

+0

@ user3369387您需要將登錄代碼放入一個名爲「login-check.php」的單獨文件中,並將HTML代碼放入另一個文件中,如「login.php」,然後將此文件中的操作設置爲「login-check」 .PHP –

相關問題