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.
Related
I have this error "Warning: mysql_result(): user_id not found in MySQL result index 13 in C:\xampp\htdocs\core\functions\users.php on line 14"
I think i don't know how to read from my Database, it looks like
Here is my users code
<?php
function user_exists($username){
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`uID`) FROM `user` WHERE `uUserName` = '$username'"), 0) == 1) ? true : false;
}
function user_active($username){
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`uID`) FROM `user` WHERE `uUserName` = '$username' AND `uActive` = 1"), 0) == 1) ? true : false;
}
function user_id_from_username($username){
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `uID` FROM `user` WHERE `uUserName` = '$username'"), 0, 'user_id');
}
function login($username,$password){
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`uID`) FROM `user` WHERE `uUserName` = '$username' AND `uPassword` = '$password'"), 0) == 1) ? $user_id : false;
}
?>
This is my login system code
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true){
$errors[] = 'You need to enter a Username and Password';
} else if(user_exists($username) == false){
$errors[] = 'We cannot find that Username, have you registered?';
} else if(user_active($username) === false){
$errors[] = 'You have not activated your account.';
}
else {
$login = login($username,$password);
if($login === false){
$errors[] = 'The username or password is incorrect';
} else {
echo 'ok';
}
}
print_r($errors);
}
You have an error at line 13 where you specify 'user_id' as an offset.
You can simply get the uID column and store the value if that row exists.
$result = mysql_query("SELECT `uID` FROM `user` WHERE `uUserName` = '$username'");
$user_id = 0; // default value, meaning user not found
if ($result && mysql_num_rows($result) > 0){
$row = mysql_fetch_assoc($result);
$user_id = $row[0];
}
return $user_id;
Then you can modify your login function to check whether user_id > 0 or not. If it's larger than 0, then you got that user's id.
Currently the only problem that I see is your user_id_from_username function.
You're trying to set an offset to a field that doesn't exist and mysql doesn't find it. So it's throwing an error:
function user_id_from_username($username){
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `uID` FROM `user` WHERE `uUserName` = '$username'"), 0, 'uID');
}
Try the above or leave off the uID since it's not a mandatory but rather an optional parameter.
Insert obligatory, you should be using mysqli instead of mysql at this point if your PHP version supports it.
So I have created a function:
function user_data($user_id) {
$data = array();
$user_id = (int)$unser_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1){
unset($func_get_args[0]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE 'user_id' = $user_id"));
return $data;
}
}
By mistake I crated a typo unser_id but didnt relise up until I had to troubleshoot further along the line in my code.
I am creating a login script but the point in which I am having to troubleshoot is showing profile data from my other users.
The reason I point out the typo part is because it for some reason is a strange error. If I change it to user_id it will not allow me to login anymore. If I leave it as under_id it works.
I am having to troubleshoot because I believe this is the cause of the problem I am having trying to view other users profiles and showing their information and not mine which is happening right now.
For example, in my url www.mywebsite.com/myprofile shows my username and my email address, if I type in www.mywebsite.com/otherprofile it still shows my information. But it does show a query if I type a user that does not exist in my database so that part works.
I believe the issue all stems form this typo but am really stuck as to appraoch a resolve?
So here is the other code:
profile page:
if (isset($_GET['username']) === true && empty ($_GET['username']) === false) {
$username = $_GET['username'];
if (user_exists($username) === true) {
$user_id = user_id_from_username($username);
$profile_data = user_data($user_id, 'first_name', 'last_name', 'email');
?>
<p><?php echo $profile_data['profile']; ?></p>
<h1><?php echo $profile_data['first_name']; ?> profile</h1>
<p><?php echo $profile_data['email'] ?></p>
<?php
} else {
echo 'Sorry, that user does not exist';
}
} else {
header('Location: index.php');
exit();
}
Here all the related functions:
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 email_exists($email) {
$email = sanitize($email);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'");
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);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password' "), 0) == 1) ? $user_id : false;
}
The problem in your first function is that you are quoting your column name with single quotes:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE 'user_id' = $user_id"));
^ ^
That means that you are not actually using the column user_id but a string.
You should change that to:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
(or without the backticks...).
Apart from that you are using the deprecated mysql_* functions and you don't have any error handling. You should switch to PDO or mysqli using prepared statements and make sure it throws exceptions (both can) so that you know exactly what goes wrong.
You are replacing the argument $user_id passed to user_data by $unser_id:
$user_id = (int)$unser_id;
This way, the value of $user_id will always be whatever is stored in $unser_id, not what is passed to the function. You should try removing the line, so the code actually uses the user id you are passing it.
If you do not have any variable called $unser_id you should check the PHP error logs. I suspect there will be lines saying something like Undefined variable: unser_id.
I am currently following a tutorial on Youtube called Register & Login/PHP tutorials by Alex from Phpacademy.. am in part 5 and here is login.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password ';
} else if (user_exists($username) === false) {
$errors[] = 'We couldn\'t find that username. Have you registered?';
}
else if (user_active($username) === false){
$errors[] = 'You havn\'t activated your account!';
}
else {
$login = login($username, $password);
if ($login === false) {
$error[] = 'That username/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location: index.php');
exit();
}
}
}
print_r($errors);
?>
Here is users.php
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username'"), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username' AND `active` = 1 ") , 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);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username' AND `password` = '.$password'"), 0) == 1) ? $user_id : false;
}
?>
and here is the output Array ( [0] => We couldn't find that username. Have you registered? )
Am new here, apologies in advance
WHERE `username` = '.$username' AND `password` = '.$password'"
Remove the dots
Your SQL queries are going to be returning bad results. Otherwise, you will be searching for .jond in your database if the username they entered is jond.
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username'"), 0) == 1) ? true : false;
Remove the . before $username and $password in the query.
"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"
Your query needs a tad bit tweaking. Remove the period in front of the username since it's inside the double quotes
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
This goes the same for the other queries in that file. As mentioned in the comments, you really ought to switch from the deprecated mysql_* functions to PDO/mysqli so that your code will still work in future versions of PHP, and you won't be open to injection hacks.
Your code is pretty hideous overall. You should NOT be nesting your mysql calls like that. Nesting like that implies that you think a DB operation will NEVER fail. This is a VERY BAD assumption.
That being said, here's at least one source of your problems:
return (...snip ... WHERE `username` = '.$username'"), 0) == 1) ? true : false;
^--- here
You've embedded a . in that query, making all your usernames look like .foo instead of just foo. The problem exists in both user_exists(), user_active() AND login().
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 ;
}
I have been trying to get the below code working for a few hours now. The idea is that it checks my database (b00543346) and the table "members" to see if a user exists (thus if their memberID is there. It then checks if a user is set to active.
At present not matter what username/password i enter and press login, this is displayed "Array ( [0] => Username Not Found. Have You Registered? )"
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'"), 0) == 1) ? true : false; //check if user id exists
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false; //check if user has activated account
}
?>
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You Must Enter a Username AND Password';
} else if (user_exists($username) === false) {
$errors[] = 'Username Not Found. Have You Registered?';
} else if (user_active($username) === false) {
$errors[] = 'You Haven\'t Activated Your Account, Please Do So!';
}
print_r($errors);
}
?>
EDIT: mysql functions in PHP do not like a space between the function name and the first open parenthesis. So count(membersID) will work, while count (membersID) will get you an error!
I'm curious what your sanitize() function is doing. If it at all modifies the username, it seems likely that your initial test data was input into the table manually and not run through the sanitize() function, then as the code sanitizes and perhaps modifies the data, it's not matching in the SQL.
You may also add some debug to your function to see a bit better what is going on. The current function is obfuscating some of what is happening. Try:
function user_exists($username) {
print "DEBUG: username=[$username]\n";
$query = "SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'";
print "DEBUG: query=$query\n";
$result = mysql_query($query);
if (!$result) {
die('Could not execute query:' . mysql_error());
}
print "DEBUG Result Set Array\n";
print_r(mysql_fetch_assoc($result));
print "DEBUG just the result now\n";
print mysql_result($result, 0);
return mysql_result($result, 0) == 1;
}
I'm not too fond of the standard SQL functions of PHP anymore, so I can't judge that. But have you tried
SELECT COUNT (*) FROM `members` WHERE `username` = '$username'