Search code examples
phpmysqlsqlsuppress-warningserror-suppression

How to suppress "is not a valid MySQL result resource" errors


I have a simple script to check how many files a user has uploaded:

$sql = "SELECT * from $username where file IS NOT NULL";
$result = mysql_query($sql);
$count=mysql_num_rows($result);

If the table $username does not have any rows where file is not null it spits out:

"Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in..."

What can I do to avoid this? Is there an easy way to simply suppress this error message from displaying? or a simple "if" statement that could prevent the SQL query from happening in the first place?


Solution

  • You could do something like this:

    <?php
     $sql = "SELECT * from $username where file IS NOT NULL";
     $result = mysql_query($sql);
     if($result) 
     {
         $count=mysql_num_rows($result);
     }
     else 
     {
         $count = 0;
      }
    

    OR use a shorthand:

    <?php 
     $count = ($result) ? mysql_num_rows($result) : 0;
    

    Note:

    Like you can see in other comment's, this is just an answer to your question, taking care of one problem at a time. The usage of $username here can be tricky, especially if it's dynamic or user generated content. It's best to look at some long term improvements to the way you interact with the database, but here's the fix for now ;-)

    PS. If you're not feeling like learning all the new stuff, perhaps a framework, something like Codeigniter could help you. Using it's active record class is easy and it takes care of a lot of things itself.