Jump to content

Having a little trouble with a MySQL result and while $row loop


kittrellbj

Recommended Posts

I am having a little bit of trouble with this piece of code.  I'm sure it's something simple, but I have been working on this thing all day and want to get it finally finished.

 

Here's the troublesome code:

 

function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
}

$sql_clean = "SELECT * complete WHERE createdate < date_sub(current_date, interval 1 minute)";
$sql_list = mysql_query($sql_clean);

while($row = mysql_fetch_assoc($sql_list)) {
    $directory = "complete/" . $row['fileurl'];
    rrmdir($directory);
    }

 

The purpose of this particular bit is to run on a cron every few days.  It gets "createdate" and other info from the "complete" table in order to know how old the record is.  If the record is older than (in the example, 1 minute; it will be set to several days on public) the defined max age, it removes that directory and everything within it to keep the directory clean and the disk usage down.

 

The error returned is

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home1/latenit2/public_html/kindleprocessor/process/garbagecleaner.php on line 46

 

Line 46 is

while($row = mysql_fetch_assoc($sql_list)) {

 

I may be doing the look-up on the MySQL database incorrectly, too.  I haven't discounted that, and I'd be thankful if someone could help me out with this issue.

This basically means your query has failed for some reason, and because you don't
check this and just carry on, you get an error.

The moral of the story here? If something can fail, check to make sure it hasn't before using any result you assume it has returned.

[code=php:0]
if ($sql_list = mysql_query($sql_clean)) {
  if (mysql_num_rows($sql_list)) {
    while($row = mysql_fetch_assoc($sql_list)) {
      $directory = "complete/" . $row['fileurl'];
      rrmdir($directory);
    }
  } else {
    // no result found.
  }
} else {
    trigger_error(mysql_error());
}

Thanks for the help.  I changed the query around to be a little more appropriate:

 

$sql_clean = "SELECT * FROM complete WHERE createdate < CURRENT_DATE() - INTERVAL 3 DAY";

 

And it works like a charm. Thanks for the help and pushing an old, tired stranger over the finish line.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.