-1

My SQL query counts the number of rows that meet a criteria. Sometimes this value is 0 or 1. This will create an error about returning a boolean.

How can this be avoided? Should I not use mysql_fetch_array?

// Query the db to count the # of comments.
$price_change_dbo = 
    mysql_query("
        SELECT COUNT(1) AS comment_count 
        FROM comments 
        WHERE user_id = '{$user_id}';"
    );

// Use the result. 
$price_change_row = mysql_fetch_array($price_change_dbo);

Here is the warning:

Warning: mysql_fetch_array() expects parameter 1 to be resource, 
         boolean given in /Applications/MAMP/... on line 1.
Shoe
  • 72,892
  • 33
  • 161
  • 264
Don P
  • 55,051
  • 105
  • 280
  • 411

3 Answers3

2

You should check whether the result ist false. That happens when an error occurs while querying the sql-command. If the result ist false, you should print the error with

echo mysql_error();

(However, you should consider using PDO or mysqli, because the mysql_ methods are deprecated).

At the end, your SQL is wrong. Delete the {} and it should work.

looper
  • 1,861
  • 25
  • 41
1

As the comments say, using the mysql_ family of functions is no longer recommended.

However, for sake of explanation of what actually happened:

mysql_query will not directly return the result of your count, it will create a resource and return a numeric identifier which other mysql_ functions will use to grab that resource.

The error message then tells you that instead of a resource, you got a boolean. Usually, this means that your mysql_query failed and returned false instead of a resource identifier.

So, you should first check to see if the result is false and behave accordingly. For example, use mysql_error to check what was wrong with the query.

Rick
  • 1,303
  • 9
  • 8
0

I think your sql query is bad:

 "  SELECT COUNT(1) AS comment_count 
    FROM comments 
    WHERE user_id = '".$user_id."'"

Those curly braces are causing an error in your query. This is causing mysql_query to not be a valid resource which is why mysql_fetch_array is complaining

Landon
  • 3,928
  • 3
  • 26
  • 40