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)
...
Related
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 3 years ago.
I'm trying to check the database for a taken username when the user signs up. The connection to the database works fine as a similar password will be added to the table.
$username = $_POST['user'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$s = 'SELECT * FROM users WHERE username = "$username"';
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if ($num == 1) {
echo "Username is taken";
}else {
table for users
It goes to the else and adds the username to the database anyways. I have checked to make sure there isn't more than one username, although a greater than sign would work better anyway. any ideas?
Your code must be using parameter binding to send the value of $username to the database, otherwise "$username" is treated as a literal string. It will also protect your from SQL injections.
It would probably be better to create a UNIQUE key on that column instead. If you want to do it in the application layer for whatever reason, you can fetch the result and use that.
$stmt = $con->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result()->fetch_all();
if ($result) {
echo "Username is taken";
} else {
// No such username in the database yet
}
This is not going to be very efficient, so we can simplify it using COUNT(1). It will return a single value containing the number of matching rows.
$stmt = $con->prepare('SELECT COUNT(1) FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$usernameTaken = $stmt->get_result()->fetch_row()[0];
if ($usernameTaken) {
echo "Username is taken";
} else {
// No such username in the database yet
}
For more explanation see https://phpdelusions.net/mysqli/check_value
$s = 'SELECT * FROM users WHERE username = "$username"';
You are using double quote inside single quote so there is no interpolation happening. Change the order to
$s = "SELECT * FROM users WHERE username = '{$username}'";
This mysqli_fetch_array not returning values. Checked it for SQL errors, none found. some error in PHP or functions I guess. Please help me correct it.
$login = login($username, $password);
if ($login == false) {
$errors[] = "That username and password combination is incorrect";
}
// validate login
function login($username, $password){
$user_id = id_from_username($username);
echo $user_id;
$password = md5($password);
$username = sanitize($username);
$query = "SELECT `password` FROM `user_data` WHERE `username` = '$username' ";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
if ($row[0] == $password) {
echo "Login successful";
return $user_id;
}
else{
echo "Login not successful";
return false;
}
}
// user id from username
function id_from_username($username){
$username = sanitize($username);
$query = "SELECT `user_id` FROM `user_data` WHERE `username` = '$username'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
return $row[0];
}
EDIT: As Lawrence correctly pointed out I missed the variable scope issue. mysqli_query does not have access to $conn variable.
Try to check the number of returned rows in the $result:
echo $result->num_rows;
Or print it to the log if you have some. Not sure how you are checking mysqli_fetch_array does not return values - try var_dump() or print_r().
Few further recommendations:
Both queries in your question select from the same table - user_data - it is pretty inefficient to do it separately (unless id_from_username is commonly used elsewhere), I'd merge that into one query to select it at once:
SELECT user_id, password FROM user_data WHERE ...
Using mysqli_query and concatenating user input into the query is usually a bad idea. Not sure what your sanitize function does but I'd still use variable binding instead, even mysqli supports that with mysqli_prepare, see here.
Based on your code you are storing passwords in database using md5. This is a very bad practice. PHP provides very nice functions password_hash and password_verify since PHP 5.5.0, they will handle password hashing for you and make your application a lot more secure.
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 :)
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.
trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.