PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 18, 2022

[FIXED] Mysql_fetch_array is showing a warning for values of 0 or 1

 February 18, 2022     lamp, mamp, mysql, php, xampp     No comments   

Issue

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.

Solution

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.



Answered By - Rick
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing