检查用户是否验证了mysql

时间:2013-01-29 06:47:42

标签: php mysql

我正在寻找用户在尝试登录时是否经过验证但是我做错了什么

$validationsql = mysql_query("SELECT Validation FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
$validationresult = mysql_query($validationsql) or die('error');
if ($validationresult == "'FALSE'")
{
         echo "<h1>Validation Error</h1>";
         die;
}

3 个答案:

答案 0 :(得分:2)

你做错了很多事。对于身份验证,您必须查看数据库中是否有客户提交的用户。要做到这一点,你必须使用类似的东西:

$validationsql = mysql_query("SELECT Validation FROM users WHERE Username = '".$username."' AND Password = '".$password."'"); //Retrives data from database
$usersfound = mysql_num_rows($validationsql) or die('error'); //counts how many records have been retrieved
/*
 *If number of data is not 1 (assuming you have unique users) validation fails
*/
if ($usersfound !== 1)
{
         echo "<h1>Validation Error</h1>";
         die;
}

如果您不使用预准备语句,则必须出于安全目的而转义数据(sql injection)。为此,您可以使用mysql_real_escape_string。在此之后,您的代码将变为:

$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$validationsql = mysql_query("SELECT Validation FROM users WHERE Username = '".$username."' AND Password = '".$password."'"); //Retrives data from database
$usersfound = mysql_num_rows($validationsql) or die('error'); //counts how many records have been retrieved
/*
 *If number of data is not 1 (assuming you have unique users) validation fails
*/
if ($usersfound !== 1)
{
         echo "<h1>Validation Error</h1>";
         die;
}

但这并不意味着你做的一切都是正确的。不推荐使用mysql_*个函数。您应该使用PDOmysqli_*函数。您还必须积极使用prepared statements.

答案 1 :(得分:0)

第一件事就是不要存储这样的密码。使用MD5或其他散列方法。

尝试以下代码

if (!$validationresult)
{
         echo "<h1>Validation Error</h1>";
         die;
}

答案 2 :(得分:0)

假设您的数据库表中有一个名为“Validation”的字段,如果不存在,则将其更改为SELECT * FROM ...

$validationsql = "SELECT Validation FROM users WHERE Username = '".$username."' AND Password = '".$password."'";
$validationresult = mysql_query($validationsql) or die('error');
if (mysql_num_rows($validationresult) == 0)
{
         echo "<h1>Validation Error</h1>";
         die;
}

更好地使用mysqli OR PDO,这是安全的。您的代码存在很多漏洞