0

Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

I get this co-occurant error and I can't figure out what to do about it:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\xampp\htdocs\Project\Func\user.func.php on line 44

The code snippet, looks like this:

42    $user_id = mysql_real_escape_string($user_id);
43    $sql = mysql_query("SELECT `username` FROM `users` WHERE user_id = $user_id");
44    $row = mysql_fetch_assoc($sql);
45    return $row['username'];

I understand that it's the mysql_fetch_assoc() command that's triggering the error, but why?

Can anyone please direct me to the error in my code? I'd appreciate any help.

Thanks.

Community
  • 1
  • 1
NorS
  • 170
  • 3
  • 14
  • There are 8 lines of code here. Which one is 44? – Pekka Sep 15 '11 at 09:41
  • I edited my question, so that only line 44 is showing. – NorS Sep 15 '11 at 09:48
  • I appreciate the intent, but we *do* need to see the lines before. Can you insert them again? :) – Pekka Sep 15 '11 at 09:50
  • I hope this edit sorts everything out? – NorS Sep 15 '11 at 09:52
  • My guess is your $user_id is "invalid". Echo it out (just before sql) and let us know if it's an actual number – Bojan Kogoj Sep 15 '11 at 09:57
  • Perfect. :) I'm not sure what the problem is here, but chances are that your query fails. See [Reference: What is a perfect code sample using the mysql extension?](http://stackoverflow.com/q/6198104) for how to add error handling. – Pekka Sep 15 '11 at 09:57
  • Try printing the whole resulting SQL and try running it in MySQL directly - see if you get any errors. `mysql_query` returns a resource if the query is successful, but FALSE if an error occurred. – Aleks G Sep 15 '11 at 09:58
  • I've overlooked the code again, and I think the problem might be that I'm trying to return "username" which is a VARCHAR. Should this be a problem? – NorS Sep 15 '11 at 10:05

2 Answers2

0

Is your code complete? The only possible types mysql_query can return is a resource or a boolean. It cannot return a string.

Often people get this when they pass an SQL query to mysql_fetch_assoc and don't run mysql_query on it firts.

Also if your user ID is an integer, you don't have to use mysql_real_escape_string, a type conversion is just fine:

$user_id = (int) $user_id;
vvondra
  • 2,807
  • 1
  • 20
  • 34
0

The query is failing, if you check the return value from mysql_query() you'll see its false. You can get the reason why by calling mysql_error() but one obvious cause is that you've not put quotes around $user_id in the SQL

symcbean
  • 46,644
  • 6
  • 56
  • 89