0

我是 PHP 和 SQL 的新手,但我正在尝试创建一个简单的 PHP 脚本,允许用户登录到网站。由于某种原因它不起作用,我不明白为什么。每次我尝试使用正确的用户名和密码登录时,都会收到错误“用户名或密码错误”。数据库名和表名是正确的。

连接.php:

<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users'; 

// Connect to server and database 
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");

// Info sent from form
$user = trim($_POST['user']); 
$pass = trim($_POST['pass']); 

// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);

$count 0= mysql_num_rows($result);
if($count==1){

// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass"); 
header("location:score.php");
}
else 
{
echo "Wrong Username or Password";
}
?>

分数.php:

<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>

<html>
<body>
<h1>Login Successful</h1>
</body>
</html>

我希望有人能找到我的错误,谢谢!

4

2 回答 2

2

仅供参考session_registersession_is_registered已弃用,将从 PHP 中删除。还尝试更改您的代码以使用 mysqli 或 PDO。很多文章解释了如何做到这一点。最后,确保您对用户的输入($_POST 数组)进行了转义,因为您永远不知道用户将发送什么,并且您不希望容易受到 SQL 注入的影响。您真的不想以明文形式存储密码,因此最好使用SHA1or MD5

写完上面的代码,你的代码就变成了(可以$_SESSION直接使用全局数组):

连接.php:

<?php
$db_host  = 'localhost';
$db_name  = 'app';
$db_user  = 'root';
$db_pass  = '';
$tbl_name = 'users'; 

// Connect to server and database 
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");

// Info sent from form
$user = trim($_POST['user']); 
$pass = trim($_POST['pass']); 

// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql  = "SELECT * FROM $tbl_name "
      . "WHERE username = '$user' "
      . "AND password = sha1('$pass')";

$result = mysql_query($sql);

// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{

    // Register $user, $pass send the user to "score.php"
    $_SESSION['user'] = $user;

    // You really don't need to store the password unless you use
    // it somewhere else
    $_SESSION['pass'] = $pass;
    header("location: ./score.php");
}
else 
{
    echo "Wrong Username or Password";
}
?>

分数.php:

<?php
session_start();
if (!isset($_SESSION['user']))
{
    header("location:login.html");
}
?>

<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
于 2012-10-29T21:49:46.963 回答
0

几件事

将此行更改为我在其下方放置的带有错误检查的行

$result= mysql_query($sql);

$result= mysql_query($sql) or die(mysql_error());

很可能有一个 sql 错误并且你没有把它捡起来,所以结果总是有 0 行

也不确定这条线是否是错字,那里不应该有 0

$count 0= mysql_num_rows($result);
于 2012-10-29T21:43:06.153 回答