I have a situation where I have to check if user exists in database, I try this:
$username = htmlspecialchars($_POST['userName']);
/* Check if username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai WHERE username = "$username"';
$result = $db_handle->query($query);
if($result->num_rows == 0) {
$error_message = "Do not exist";
}
}
}
But It doesn't work. It always returns 0 rows even if I enter a valid username that exists in database.
mysqli_result Object ( [current_field] => 0 [field_count] => 7 [lengths] => [num_rows] => 0 [type] => 0 )
Then I have second script, where I check if username is free, that works just fine:
$username = htmlspecialchars($_POST['userName']);
/* Check ir username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai where username = "$username"';
$result = $db_handle->query($query);
if(!empty($result)) {
$error_message = "Exists";
}
}
}
Could you help me out with this? Can't figure it out on my own.
EDIT: When I enter the username manually it just works fine. So the problem is with the variable in the query. But I don't get It. Why It works on one query but not the other....
$query = 'SELECT * FROM naudotojai WHERE username = admin';