Unable to solve PHP error message - php

Can anyone please help me with the following error. I am making a register and login function for my website. I have it connected to my local database and in there I have created a user. When I test that I can login and that username and password is recognised, it works as expected. But I get this error
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 17 in C:\xampp\htdocs\LoginAndRegistration\core\functions\users.php on line 34
And this is what I have on line 34
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Which is part of the following function
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
}
Ive been staring at it for ages now but cant seem to figure out the problem. Can anyone tell me what I am doing wrong?
Thanks

That line of code looks like that you want to check does username and password exist. You need to change your code to this:
return (mysql_result(mysql_query("SELECT COUNT(id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Also change (id) to your id name of column.

This error means the query failed. Always check if the query succeeded:
$q = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if ($q) {
if ($rows = mysql_num_rows($q)) {
// Continue operation, or set a flag
} else {
// No matching rows, throw an Exception or set a flag
}
} else {
// Something is wrong
die(mysql_error());
}

Your error probably comes from the fact that the query did not return any result at all because there was none with matching username and password.
I would really not stuff that much functions into each other. It looks overcomplicates, it does not leave any room to add error handling (like handling the case that is supposed to happen in your case), and it messes up PHP'S error reporting, because any error happening will be on the same code line.
Spread stuff out into multiple lines. It makes things clearer for you any anybody that reads your code, in enhances debugging activities, and is generally a good idea because of the lower line length.

You are getting a warning (not an error) because mysql_query at some times, it won't return any rows, so trying to get the first row with mysql_result when there are not rows, will raise the warning.
You can try:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($query) > 0)
return true;
else
return false;
}

With the depreciation argument aside, use mysql_num_rows instead of mysql_result.
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'")) == 1) ? true : false;
}

try this
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'") ;
if (mysql_num_rows($query) > 0 ) {
$data = true ;
}else {
$data = false ;
}
return $data ;
}

Related

php: mysqli login script failing for unknown reason

So I have my log in script that I am trying to get to work, but when I try to log in it always says no even if the test I included below says expected:(password hash here) found: (same password hash here) I have changed the code so many times in attempts to fix it, and done a load of Google searches(for those who want to give me lmgtfy links) trying to fix it. I've included as much of the code as I can without having to add fake details so stack overflow would let me add more code:
Actual script:
else{
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username/password is incorrect';
} else {
echo "ok";
$_SESSION['user_id'] = $login;
header('Location: index2.php');
exit();
}
}
print_r($errors);
//echo "expected to see: ". $pass. " "; //this was a test
//echo "found: ".$passen; //this was too
Login function:
function login($username, $password){
$user_id = sanitize($username);
$db = get_my_db();
$username = sanitize($username);
$password = md5($password);
$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
return ($db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'") === 1) ? $user_id : false; }
And the sanitize() function is just mysqli_real_escape_string($data) if you want anything else, let me know, and i'll put it in. By the way, the tests script was this: and the expected function just turned the $password into an md5.
$res = $db->query("SELECT `password` FROM users WHERE username = '$username'");
$row = $res->fetch_assoc();
$pass = $row['password'];
$passen = expected($password);
I do not know where it fails, but a few tips:
use salted sha1 passwords
do not create functions like sanitize(),get_my_db(), those dont even speedup your work
mysqli_ should be called with $con first parameter, like mysqli_real_escape_string($con, $var);
to get working global $con in local function, write function
login() { global $con; }

mysql_result to mysqli issue

ive tried in vain for a good amount of time to convert this string from mysql to mysqli with no luck. here is what i had for mysql :
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
ive tried:
function user_exists($username) {
$link = mysqli_connect("localhost", "username", "password", "table");
$username = sanitize($username);
$usernamequery = "SELECT COUNT(`userid`) FROM `table` WHERE `username` = '$username' ";
$query = mysqli_query($link, $usernamequery);
$queryarray = mysqli_fetch_array($query, MYSQLI_BOTH);
$queryarrayres = mysqli_num_rows($query) ;
if ($queryarrayres > 0) { true; } else { false;}
}
numerous hits of this issue on here from previous users but none of them seem to work for me.this and this for example. it all seems fine until i get to converting the mysql_result query and it goes to pieces. i understand that mysql_result in the above situation is essentially checking to see if theres one row selected and thats it equal to one, ie present, but i just cant seem to get something equivalent in the mysqli.
function login($username, $password) {
$link = mysqli_connect("localhost", "username", "pw", "db");
$username = sanitize($username);
$password = md5($password);
$loginquery = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = $username AND `password` = $password";
$query = mysqli_query($link, $loginquery);
$queryarray = mysqli_fetch_array($query);
$queryarrayres = $queryarray[0];
return ($queryarrayres > 0)? $userid :false;
}
in this instance, $queryarrayres prints as 1 at the right occasion, and zero the rest. so that bit works. the function actually contains a password element too, which ive added.
unfortunately when i use the function is continually returns false. i have tested on a test page, and if i change $username and $password to absolute variable its seems to work. the code is identical between the old version (not shown), and this version, aside from the obvious mysqli updates. this narrows the issue down to three possibilities. 1) something to do with $username and $password population. 2) the $usernamequery string. 3) the return of the function. i reckon its three given that no other code has changed, but i cant put my finger on whats going on here.
Use this function below, it works
function user_id_from_username ($username){
global $connect;
$username = sanitize($username);
$query = " SELECT user_id FROM users WHERE username = '$username' ";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo $row["user_id"];
}
Your new user_exists function is not returning anything.
change
if ($queryarrayres > 0) { true; } else { false;}
to
return ($queryarrayres > 0)?true:false;
You may use the following function and call the function
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}

How to login with bcrypt

I want to change my register/login pages from md5 to bcrypt. The register part is allright but I can't get the login part working good.
I am trying to work with a bcrypt library;https://github.com/ircmaxell/password_compat/blob/master/lib/password.php.
The original login function(without md5) looks like this;
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
return (mysql_result
(mysql_query
("SELECT COUNT(`user_id`)
FROM `users`
WHERE `username` = '$username'
AND `password` = '$password'"), 0) == 1) ? $user_id : false;
}
What I am trying to do is retrieve the database but with the original code is is not possible because of the mysql_result part.
I thought for example that;
function login($username, $password) {
$username = sanitize($username);
$user_query = mysql_query("SELECT `password` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_assoc($user_query);
$hash = $row['password'];
password_verify($password, $hash);
}
would solve this problem, but it isn't.
Is there a solution without mysql_fetch_assoc() here or am I trying to retieve the database wrong?
You need to set up password_verify like so :
function login($username, $password) {
$sql = "SELECT * FROM users WHERE username = :username"; // Select all info related to the USERNAME
$loginQ = $dbh->prepare($sql); // Prepare your query
$loginQ->bindParam(':username', $username); // Bind your variable
$loginQ->execute(); // Execute (TRUE or FALSE)
if ($loginQ) { // If TRUE
if ($loginQ->rowCount() == 1) { // You should only be returning 1 row with 1 username
$row = $loginQ->fetch(); // Fetch that row
$hash = $row['password']; // Use the row password and assign it to a variable
if (password_verify($password, $hash)) { // use passwd_compat function password_verify to check if it passes, if it does return TRUE
return TRUE;
}
}
}
}
Just from reading your code the issue I first noticed was that you are not returning a value whether it be
TRUE
or
FALSE
Also for another way to understand how to use password_verify you can also do it like so :
if (password_verify($form_password, $row['password'])) {
$_SESSION['LoggedIn'] = TRUE;
header("location: homepage.php");
} else {
Echo "Wrong password or username please <a href='index.php'><b>Retry!</b></a>";
}
and the next issue I noticed is that you are using unsafe and old functions (mysql_)
To help you with the later of the issues above I made a PDO version for you to use which has many more positives then mysql_ does.
Then to set up PDO look at this answer (yes it is mine - there a lot of good answers out there so do some research) This gives your the steps from setting up the PDO instance to actually using it. Any questions just ask.
More on PDO here.

PHP boolean error

Im a newbie to php trying understand why i get boolean error in my specific case with a code that works for others. I have a function that returns a $user_id which is to be used in a session later on. Here is he function:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = sha1($password);
return (mysql_result(mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;
}
This always results in a fail, with this error: Warning: mysql_result() expects parameter 1 to be resource, boolean given in. with a line number that points to this line.
return (mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;
Why does this fail ? Isn't this enough to check weather the query was successful and test result. DB connection and sql query seemed to be correct, doesn't matter whether i use ' or omit. After several hours of research i managed to remove the error with an if statement. Like so :
function login($username, $password) {
$user_id = user_id_from_username( $username );
$username = sanitize( $username );
$password = sha1( $password );
$result = mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username'AND password = '$password'");
if ( $result == 1 ) {
return $user_id;
} else if ( $result == 0 ) {
return false;
}
}
I would like to know why the second function works and not the first. Do you have to use an if statement to check the query ? If there is a better way to write this function please suggest.:)
Probably you have error in query so mysql_query return false
Replace:
return (mysql_result(mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;
with:
$result = mysql_query("SELECT COUNT(user_id) as count FROM users WHERE username = '$username' AND password = '$password'") or die(mysql_error());
return (mysql_result($result, 0, 'count') == 1) ? $user_id : false ;
and you will see mysql error.

cannot login when username and password are correct

Hello so I am doing this tutorial from php academy for a php and mysql login and registration form. It was going okay.. he was showing how to idk what the correct way to say it but to create functions to echo errors.. yeah that sounds right. So the first couple errors echoed correctly but the one to actually validate the user_id and whatknot, isn't working. Its showing the error I created when the username and password combination is incorrect even when i submit the correct information. I've created a few dummy users and none of them can get through.
this is my code..
include 'core/init.php';
include 'includes/overall/header.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Uh oh! You forgot to enter your username and password';
} else if (user_exists($username) === false) {
$errors[] = 'Who is that? Have you registered?';
} else if (user_active($username) === false) {
$errors[] = 'Account is not activated.';
} else {
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username and password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location:index.php');
exit();
}
}
print_r($errors);
}
include 'includes/overall/footer.php';
and
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1");
return (mysql_result($query, 0) == 1) ? true : false;
}
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
return (mysql_result($query, 0) == 1) ? $user_id : false;
}
does anyone know what I am doing wrong? I've tried a few things and nothing works. For example in the video he does it a little different and puts his queries in line but that was giving me errors so i did it the way he originally had it and made the queries variables (i only have somewhat of an idea what I'm actually saying haha).. but that fixed the errors. I tried doing that to the other functions (not shown) but that caused a whole lot of errors :(
is it something really dumb? I had a similar problem before that I figured out was due to a missing semi colon but I've stared at this stupid code for so long and haven't found anything.. I re-watched the videos in the tutorial series that explain all this like 10 times each.. my eyes feel like they are going to bleed or explode. Some of the comments show that others are having similar issues.. help?
I'm new to all this php mysql stuff so.. I wont be offended if u speak to me like a child.. in fact its appreciated.
thanks.
Do I understand correctly that you are unable to login now?
I had similar problems in the past. I do not see your mistake but I will share a method that allowed me to find mistakes.
Store the MySQL query in a variable as a string and data inputted from a form
echo that variable
Test the outputted string in phpMyAdmin - if the query is wrong it will give you a hint what is wrong with it.
Also it might be worth testing the queries with "LIKE" instead of "="
eg.
.....FROM `users` WHERE `username` LIKE '$username'.....
This is my code:
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT * FROM `users` WHERE `username` = '$username' "),0) ==1) ? true : false;
}

Categories