-
[Mysql] Help
What is the correct way to write this query if you're trying to write a login script that verifies BOTH the username and password, this seemed logically, but did not work.
SELECT username,password FROM Users WHERE username = '$username' AND password='$password'
Could anyone tell me how to rewrite please? So that is requires both the username and password to be correct before it logs you in.
-
You need to get the row that contains the username (assuming usernames must be unique). Then call the password column and compare the inputed password with the password that's in the column. In other words, the query should only call the row that has a certain username, and AFTER that you check to see if the password matches. That's my thought at least.
-
Example please? Edit:: Oh snap, got it work, thanks bro.
-
Code:
<?php
$con = mysql_connect("localhost","peter","abc123");
$username = "riddle";
$password = "1234";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM AccountsTable WHERE username=" . $username);
while($row = mysql_fetch_array($result))
{
if (row['password'] == $password) echo "Correct password!";
}
mysql_close($con);
?>
That looks right. Took example from PHP MySQL Where Clause and edited a few things.
-
I got it to work, but i did it much more sloppy, I'll borrow your code and use it as an example, thanks!
-
mycode
Code:
$result = mysql_query("SELECT username FROM Users WHERE username = '$username'");
$result2 = mysql_query("SELECT password FROM Users WHERE password = '$password'");
if(mysql_num_rows($result) !== 0)
{
if(mysql_num_rows($result2) !== 0)
{
echo "You have sucessfully logged on!";
}
else
{
echo "Invalid username or password!";
}
}
else
{
echo "This username does not exsist";
}
}
?>
-
I don't recommend making two requests to MySQL. If you have a big database, it will consume too many resources just for the login script. Make a single request and get all of the user data in that single request. Then compare passwords, simple as that.