Log in

View Full Version : PHP user_id_from_username function HELP



szucsy11
10-15-2012, 04:07 PM
Hello.

When i try to log in it says " Warning: mysql_result(): user_id not found in MySQL result index 9 in C:\xampp\htdocs\lr\core\functions\users.php on line 10"

How do i fix this?

Here is the code:

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');


}

Thank you.

ggalan
10-15-2012, 08:21 PM
why dont you try backticks insted of single quotes for username
return mysql_result(mysql_query("SELECT (user_id) FROM users WHERE `username` = '$username'"), 0, 'user_id');

traq
10-16-2012, 12:17 AM
right - what's happening is that you're getting an error, but you're not checking for it. Even if you fix this, you'll have the same problem if you ever ask for a username that doesn't exist (and therefore, no rows are returned).

You need to check for your result before you try to use it:
function user_id_from_username( $username ){
$username = sanitize( $username );
// do the query first
$result = mysql_query( "SELECT `user_id` FROM `users` WHERE `username` = '$username'" );
// if there was an error, or no results, $result will be FALSE.
// if $result is not false, then you know there was a row returned
if( $result ){ return mysql_result( $result,0 ); }
// if you get to this point, that means there was no result.
// you could also return something like "Guest" or "Unknown User" instead.
return false;
}

--------------------------------------------------
# If at all possible, you should avoid using the mysql_* functions. #
ext/mysql is outdated and scheduled for deprecation. It is no longer recommended for new projects, and existing code should be updated to avoid performance and security problems. Using ext/mysqli (http://php.net/mysqli) or the PDO class (http://php.net/pdo) is recommended. Read more about choosing an API (http://php.net/mysqlinfo.api.choosing) here.