我的代码有一段时间。我对此并不熟悉,我正在努力奋斗。
我有几个问题,首先,一个问题是,我试图使用连接到SQL数据库的登录表单,但是当输入不正确的数据或没有数据时不会收到错误,但是它看起来是登录的。
其次,当用户登录时,我试图在每个页面上显示用户名,这是可行的,但只适用于手动输入数据库的用户。任何已通过我的注册表格添加的用户,不要显示,尽管他们显示在phpmyadmin中。
我的登录页面第一个问题的代码是:
<?php
echo '<h3>Sign in</h3>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="Username" />
Password: <input type="password" name="Password" />
<input type="submit" value="Sign in" />
</form>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
$sql = "SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
header("location:index.php");
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
{
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['UserID'] = $row['UserID'];
$_SESSION['Username'] = $row['Username'];
}
echo 'Welcome, ' . $_SESSION['Username'] . ' <a href="index2.php">Proceed to the forum Home page</a>.';
}
}
}
}
?>谢谢你的建议。
发布于 2016-07-06 04:20:27
函数mysql_query()在出现实际mysql错误时返回FALSE。这可能是语法错误、无效的约束插入或输入数据类型不匹配。如果任何插入的用户名和密码组合可能是有效的,这意味着不会有任何错误。
在您的示例中,如果用户名或密码错误,则意味着返回0行(没有数据)--即而不是a error。因此,在您的代码中,变量$result从来不是FALSE,这就是为什么您的代码从不陷入错误循环的原因。
为了解决这个问题,您需要更改代码以检查返回的行数是否大于0,而不是检查结果是否为TRUE。您可以通过使用mysql_num_rows()函数来实现这一点。
更改后的代码应该如下所示
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if($num_rows < 0){
//put some code for error
}进一步注释:
如果不想使用PDO,可以使用mysqli而不是mysql。此外,您还容易受到sql注入的影响。如果您了解一下准备好的陈述,以及如何使进入服务器的数据更加安全,那就太好了。
https://stackoverflow.com/questions/38205299
复制相似问题