SQL Query username:password - php

Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)

If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();

I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);

You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.

$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)

Related

why my MySQL queries executed before PHP Conditional check?

I'm learning to create conditional event where sql checkout data where is exists before inserting data so they don't conflicted.
i've tried using mysql row check in php then check if query empty before i tried to validate the query executed properly.
also trying to close db connection when conditional satisfied but it worthless anyway.
$user = addslashes(strtolower($usr));
$mail = addslashes(strtolower($mail));
$pass = md5(addslashes($pwd));
$check = $db->query("SELECT EXISTS(SELECT *
FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
if (!$check) {
$db->close();
return false;
} else {
$sql = "INSERT IGNORE INTO `users` (`username`, `password`, `email`)
VALUES ('$user', '$pass', '$mail')";
$query = $db->query($sql);
$db->close();
return true;
}
I'm expecting it execute my queries while data was empty and return false while data has been existed.
Your main issue is that $check will always be a truthy value, so long as the query never fails. If the query returns 0 rows, it is still a true object.
You should instead check if there were any values returned. You can also simplify the query quite a bit, given that MySQL is case-insensitive, and you don't need to check if the result exists. Using a prepared statement, the code would look like this
$stmt = $db->prepare("SELECT username FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $usr, $mail);
$stmt->execute();
$check = $stmt->fetch();
$stmt->close();
// True if the user exists
if ($check) {
return false;
} else {
$stmt = $db->prepare(" INSERT INTO users (username, password, email) VALUES (?, ?, LOWER(?))");
$stmt->bind_param("sss", $usr, $pass, $mail);
$stmt->execute();
$stmt->close();
}
That said, you should not use md5() for passwords - use password_hash() with password_verify() instead.
you can change your code like this
$check = $db->query("SELECT EXISTS(SELECT * FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
$check = $conn->query($sql);
$value = $check->fetch_row()[0];
if($value > 0 ){
echo "existed".$value; // you can change accordingly
}else{
echo "doesn't exist"; // this also
}
Because database respond the query in 1 for exist and 0 for non-exist so the num_row will be always 1 thats why we cant determine the existence with num_row so we have to fetch the value.

can someone tell me how to count the select prepare statement returns?

The problem is, I have a statement like this one below and i use it in server side of my android app
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$rows = mysqli_stmt_fetch($result);
And I want to know how many rows are back from it so I can know if there is already data in the database with the same username and email or not, but it doesn't work.
How to solve this problem? And thanks in advance.
And I want to know how many rows are back
Nope, you don't. That's a false goal.
When working with a database, you should always request the exact data you need, instead of doing some calculations on the client side.
So in your case you need the user info - so select that info. Means this very user info you can use to tell whether your query returned anything or not.
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
mysqli_stmt_execute($statement);
$result = mysqli_get_result($statement);
$user = mysqli_fetch_assoc($result);
//now you have the very $user variable to tell whether anything was found
if ($user) {
//user exists
}
All you are missing is to use the num_rows function with the resulting mysqli object:
$statement = mysqli_prepare($con,
"SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$numbRows = $result->num_rows;
//printing the result:
echo "number of rows = {$numbRows}<br>";

Mysql using where clause with Binary data type

I am learning how to encrypt user passwords in my database. I have opted for the SHA-256 hash method using a Salt and the encryption takes place just fine.
I am currently working with a test table on database that only has two fields, here is the create statement.
create table test(
id int auto_increment,
password binary(70),
primary key(id))
In my php, I use the following code to encrypt my passwords:
<?php
include 'connection.php';
$id = $_GET['id'];
$userspassword = $_GET['password'];
$salt = "Th!s$a1tis4Test1ng";
$password = hash('sha256', $salt.$userspassword);
$sql = "insert into test (password) values (?)";
if($stmt = $conn->prepare($sql)){
$stmt->bind_param("s",$password);
$stmt->execute();
echo "stored</br>";
}
$stmt->close();
mysqli_close($conn);
?>
then i later try to see if I get any match using the following php:
<?php
include 'connection.php';
$id = $_GET['id'];
$userpassword = $_GET['password'];
$salt = "Th!s$a1tis4Test1ng";
$password = hash('sha256', $salt.$userpassword);
$sql = "select id from test where password = ?";
if($stmt = $conn->prepare($sql)){
$stmt->bind_param("s",$password);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0)
echo "user found";
else
echo "not found";
}
$stmt->close();
mysqli_close($conn );
?>
Nothing happens, I always get the "Not Found" message.
I even tried matching the passwords directly withing my phpAdmin by retrieving one of the passwords and using a simple select statement to see if it will return any result.
select
id
from
test
where
password = 'someEncryptedPassword'
No results still, even when I can see that the passwords do match but I get no results. Please help, what am I doing wrong?
The issue is that you're comparing a string to a binary object. Change the type of your field to CHAR(64) and it should work.
Try this
$password = hash('sha256', $salt.$userpassword);
$sql = "select id from test where BINARY password = ?";
https://dev.mysql.com/doc/refman/5.0/en/charset-binary-op.html

Get one value from mysqli

Do I have to put results from a query into an array if I know I'm only going to receive one password from the database? I'm using:
$sql = 'SELECT password FROM users WHERE userName="'.$username.'" LIMIT 1';
$result = $con->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$hash = crypt($password,$row[0]);
if($row[0] == $hash){}
if you have stored hash in database (which you should) then you don't have to hash it again. also use prepared statement on user input.
$sql = $con->prepare("SELECT password FROM users WHERE userName=? LIMIT 1 ");
$sql->bind_param("s", $username);
$sql->execute();
$sql->bind_result($password_db);
while ($sql->fetch()) {
$hash = crypt($password,$password_db);
if($password_db == $hash){}
}
http://www.php.net/manual/en/mysqli-stmt.prepare.php
You could use list instead:
list($passwd) = $result->fetch_array(MYSQLI_NUM);
if($passwd == $hash) {
};
Here's the PHP reference
Since $result->fetch_array(MYSQLI_NUM) is returning an array type, you could reference it directly:
if($result->fetch_array(MYSQLI_NUM)[0] == $hash)
...

PHP/MYSQL Retrieve Name based on another criterion

So I have a login system and I want to retrieve the first name of the person who is logged in. Here's my php:
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT `First Name`, Username, Password
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
return true;
$stmt->close();
}
else {
// User doesn't exist
return false;
$stmt->close();
}
}
this is part of a class who has 1 private variable $conn. The login works perfectly but i just want to get the person's first name. How do I do that?
First off, NEVER grab the password from the database, that is just extremely bad practice.
Second, you only want to accept the user as correct if ONLY one row is returned.
lastly bindColumn is what you're looking for.
<?php
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT `First Name`, Username
FROM table
WHERE Username = :un AND Password = :pwd";
// Don't limit the query to only one, if there is a chance that you can
// return multiple rows, either your code is incorrect, bad data in the database, etc...
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
// Only assume proper information if you ONLY return 1 row.
// Something is wrong if you return more than one row...
if ($stmt->rowCount() == 1) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$stmt->bindColumn('Username', $username);
// You can now refer to the firstName and username variables.
return true;
$stmt->close();
} else {
// User doesn't exist
return false;
$stmt->close();
}
}
?>
That should work for you.
just change the query statement?
$query = "SELECT `First Name`
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";
if that throws errors, you would have to show more of what the class is doing to manage the db transaction
just change this line, to select only First Name in the query:
$query = "SELECT `First Name`, Username, Password
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";`
to
$query = "SELECT `First Name`
FROM table
WHERE Username = :un AND Password = :pwd
LIMIT 1";`
You need to bind the result as below
if ($stmt->rowCount() > 0) {
$stmt->bind_result($fname, $uname, $pwd);
$stmt->fetch()
echo $fname // here you get firsname
// either you can return this $fname or store into session variable for further
// User exist
return true;
$stmt->close();
}
else {
// User doesn't exist
return false;
$stmt->close();
}
In the section where you are returning true you could instead return the actual user data (and array with data will evaluate to true anyway).
Word of warning, you should use hashed passwords. Do not store the password y plain.

Categories