MySQL Check if username and password matches in Database [duplicate] - php

This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed 11 months ago.
I have a form which has a textbox with the name attribute username and another one with the name attribute password.
I also have a database with columns called user and pass. When my users signed up it added the username to the user column and password to the pass column.
How would I make a MySQL query to check if the form submitted the right username and password and then if it did have a branch to let me input the code for if it succeeded?
I really need some code, this bit isn't going well I know it should be something like SELECT * FROM table WHERE username == $username AND... but then I'm stuck because I have an MD5 password in the database and that first bit is probably wrong. Please help. :)
Thanks

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);
if ($user&&$pass)
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
//while loop
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
else
die("incorrect username/password!");
}
else
echo "user does not exist!";
}
else
die("please enter a username and password!");

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1

1.) Storage of database passwords
Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?

Related

How can I verify a form with an SQL databse?

So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.

PHP MySQL: issue selecting different columns from the same table

This has surely come up before but I haven't found a solution. I am trying to select username and password from a database to verify users a simple login script. It should simply find a row in the users table with a username and password matching those submitted through the login form.
I can match the username without any problem but not the password and I have no idea why.
The table contains columns called "username" and "password" and there is only 1 row in the table with a username 'admin' and a password 'testpassword'.
Here is the function containing three options - options 1 and 4 work, the other two don't. Option 2 is the same as option 1 except it looks up a different column. I have checked that the column name in the query matches the columns in the table and that the submitted values match. I'm not getting any error messages and can't see what might be wrong (something basic, I'm sure...).
function new_session ($username, $pw, $inactive) {
// echo statements verify that variable match database values
echo "<h2>username = " . $username . "</h2>";
echo "<h2>password = " . $pw . "</h2>";
echo "<h2>inactive = " . $inactive . "</h2>";
$db = mydb::getConnection();
//option 1
$statement = $db->prepare('SELECT * FROM users WHERE username = :parameter');
$statement->bindValue(':parameter', $username);
//option 2
//$statement = $db->prepare('SELECT * FROM users WHERE password = :parameter');
//$statement->bindValue(':parameter', $pw);
//option 3
//$statement = $db->prepare('SELECT * FROM users WHERE password = :parameter1 AND username = :parameter2');
//$statement->bindValue(':parameter1', $username);
//$statement->bindValue(':parameter2', $pw);
//option 4
//$statement = $db->prepare('SELECT * FROM users WHERE username = "admin" AND password = "testpassword"');
$statement->execute();
$row = $statement->fetchAll();
if (count($row) == 1) {
// SESSION data is set here for options 1 and 4
}
}
First thing you need to check is if the passwords in your data base are hashed. They probably should be, and if they are you need to compare using the hashing function PASSWORD
$statement = $db->prepare('SELECT * FROM users WHERE password = PASSWORD(:parameter)');
$statement->bindValue(':parameter', $pw);
Now, if your passwords aren't hashed (shame on you), you might have a different problem. As you can see in the above, password is a function name in mysql. It might be having problems parsing your statement because you are using password as a column name. Put tick-marks around the column name password. Like this:
$statement = $db->prepare('SELECT * FROM users WHERE `password` = :parameter');
$statement->bindValue(':parameter', $pw);
Notice that those are tick marks, not a single quote. They are found on the same key that ~ is on, above the tab key. These tick marks will indicate that password is a column name.
The word "PASSWORD" is a mysql command. so escape it first like this:
//option 3
//$statement = $db->prepare('SELECT * FROM users WHERE `password` = :parameter1 AND username = :parameter2')
If this query gives error, then I think you have your password encoded.
Then use this for md5:
$statement->bindValue(':parameter', md5($pw));
And for sha1:
$statement->bindValue(':parameter', sha1($pw));
I see no other errors which might could result in no rows :o
Thanks for all the suggestions and taking time to look at this, I have escaped the word password as suggested however I'm ashamed to say the problem was that the maxlength on my password form input was trimming the last character and I didn't spot it.

PHP id and password verification

I'm trying to do a simple login, which compares the input of the ID and password by the user with the data in the database
//getting the inputs
$checkid = $_POST["id"];
$checkpassword = md5($_POST["pass"]);
//getting the id and password of the id and password of the inputs
$query = "SELECT id, password FROM login WHERE id=$checkid AND password=$checkpassword";
$res = mysqli_query($link, $query);
$nres = mysqli_num_rows($res);
//$nres should be 0 if the user inputs the right id but the wrong password
//or viceversa, the only way that it $nres!=0 is that both inputs match the db, right?
if ($nres == 0) {
header('Location: http://localhost:8888/login/login_fail.php');
else
header('Location: http://localhost:8888/profile/profile.php');
exit();
it doesn't work, even if i put the right ID and the password that are on the database it will redirect to login_fail.php.
Note: it does work if i do it just with he ID and take out of the query " ,password" "AND password = $checkpassword". Help
Add quotes to your variables:
"SELECT id, password FROM login WHERE id='$checkid' AND password='$checkpassword'"
^ ^ ^ ^
Sidenote: Don't use md5, it's now insecure to use as password storage.
For password storage, either use bcrypt or PHP's password() function.
And see this article also
Also noted in comments by others, use mysqli_real_escape_string():
$checkid=mysqli_real_escape_string($link,$_POST['id']);
Try the query:
$query = "SELECT id, password FROM login WHERE id='".$checkid."' AND password='".$checkpassword."'";

MySQL statement not finding a row with matching data

On a recent project I am having issues when matching a password in the database.
The query is as follows:
mysql_query("SELECT * FROM user_accounts WHERE username = '$username' AND password = '$encryptedPass'")
This outputs
SELECT * FROM user_accounts WHERE username = 'T-McFarlane' AND password = 'äê1\Y¸c'
It can find me with just the user but with the password it cannot. I have echoed out both the database password and the encrypted password provides and they are exactly identical - this is what is in the database but it cannot find the matching row.
My question is that does this password contain any special characters or would there be any other reason that this is failing?
I have tried both utf8_swedish_ci and latin1_swedish_ci for my collation setting in the database.
You need to escape special characters in the string:
$username = mysql_real_escape_string($username);
$encryptedPass = mysql_real_escape_string($encryptedPass);
mysql_query("SELECT * FROM user_accounts WHERE username = '$username' AND password = '$encryptedPass'")
However, it would be even better to switch to PDO or mysqli, and use parametrized queries.

Check login script letting in guests?

For some reason my check login script is letting in guests.
I have not made the site live yet so its all good.
I check the database for the username and the password the user puts in the html form but for some reason if it don't even get a result it still sets the username to nil
if it gets the result it sets the username to the username but if it don't get any results it sets the username to nothing.
I have a if statement but still setting it.
$myusername = mysql_real_escape_string($_POST['myusername']);
$mypassword = mysql_real_escape_string($_POST['mypassword']);
$sql = "SELECT * FROM users WHERE username='$myusername'";
$result = mysql_query($sql) or die(mysql_error());
$battle_get = mysql_fetch_array($result);
if ($battle_get['password'] == $mypassword)
{
$_SESSION['username'] = $myusername ; // store session data
header('Location: http://mydomainname.net/new_rpg/dashboard.php');
} else {
echo "wrong password" ;
}
You don't check if the user account actually exists. You just blindly fetch a row from the result set, even if that result set has NO records in it. That means $battle_get will be an empty array (or a boolean false if the query failed). You then do a string comparison against the submitted password. If that password is also empty, you're doing if (empty == empty) and boom... the user's in.
What you SHOULD be doing is:
$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) or die(mysql_error());
if (mysql_num_rows($sql) != 1) {
die("Invalid username and/or password"); // don't tell the user which failed.
}
Checking how many rows were returned is critical - if no rows are returned, then the user doesn't exist or the password is wrong. If 1 row is returned, then it's a valid login. If more than 1 row is returned, you've got duplicate username/password pairs in the database and need to fix that right away.
And, having just seen your "md5 is hard" comment above: You're dead wrong. MD5 is trivially EASY.
When you create the user record, you can hash the password easily:
INSERT INTO users (password) VALUES (MD5('$password'));
and for the login check:
SELECT ... WHERE (password = MD5('$password'));
Nothing to it at all.
Yur mistake:
Say I am not a user.
So $battle_get['password'] = false;
and $mypassword is also false,
so $battle_get['password'] equals $mypassword
Two way you can resolve this.
First, chek the password with sql:
$sql = "SELECT * FROM users WHERE username='$myusername' AND password = '$mypassword'";
or
if(!$battle_get) {
echo "wrong password" ;
}

Categories