用户名和密码错误

时间:2013-06-06 20:11:27

标签: php login

我创建了以下代码,供人们在网站上登录,但结果一直在说:

  

用户名或密码错误

我不知道什么是错的。数据库有一个表"客户"列名称"用户名"和"密码"。

<?php
$host = ""; // Host name
$username = ""; // Mysql username
$password = ""; // Mysql password
$db_name = ""; // Database name
$tbl_name = "clients"; // Table name
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT `username` FROM `clients` WHERE `username`='$myusername' and         `password`='$mypassword'";
$result = mysql_query($sql) or die(mysql_error());

// Mysql_num_row is counting table row

if ($result) {
    $count = mysql_num_rows($result);
}
else {
    $count = 0;
}

// If result matched $myusername and $mypassword, table row must be 1 row

if ($count == 1) {

    // Register $myusername, $mypassword and redirect to file "login_success.php"

    session_register("myusername");
    session_register("mypassword");
    header("location:source/login_success.php");
}
else {
    echo "Wrong Username or Password";
}

?>

4 个答案:

答案 0 :(得分:5)

问题在于:

$username = $_POST['myusername'];
$password = $_POST['mypassword'];

$myusername = stripslashes($myusername); // Using uninitialized '$myusername'
$mypassword = stripslashes($mypassword); // Using uninitialized '$mypassword'
传递给$myusername后,

$mypasswordstripslashes()会被统一化,因此结果将始终为空。

要解决此问题,请调整传递给stripslashes()的变量名称:

$myusername = stripslashes($username);
$mypassword = stripslashes($password);

答案 1 :(得分:1)

改变这个:

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);

到此:

$myusername = stripslashes($username);
$mypassword = stripslashes($password);

答案 2 :(得分:0)

最好不要在会话中注册密码。更好的做法是使用用户的id设置会话(比如在mysql表中,你有:id,username,password等)。这是一种更好,更安全的方法。然后,在您需要登录的页面上,您只需:

<?php

session_start();
if(!isset($_SESSION['id']) {
..... display error message and redirect user to login page....
}
?>

答案 3 :(得分:-1)

$ username = $ _POST ['myusername'];

$ password = $ _POST ['mypassword'];

尝试这个

$ myusername = $ _POST ['myusername'];

$ mypassword = $ _POST ['mypassword'];