PHP to SQL interface issue

I'm using a php script to act as a go-between for some wifi'ed arduinos and an SQL database. I have multiple other sections of code that query the database and change data, however this particular segment is throwing an error whenever the conditions are met for it to run (aka there is no error and at least one result in the query) and I can't for the life of me seem to figure out why. It is not a problem with the connection to the database, as a similar query later in the code works fine every time. I have checked both the resource type and number of rows via echo after the query and both come back as expected. Can you see any reasons that might be causing the following error?

Code section:

$errorFlag = 0;
$result = 0;
$counter = 0;
$sql = "SELECT * FROM Data WHERE Last_Update < DATE_ADD(NOW(), interval -1 MINUTE)";
while (!$result && $errorFlag == 0) {
  $result = mysql_query($sql);
  $counter = $counter + 1;
  if ($counter > 30) {
    $errorFlag = 1;
    echo "#E01,".$counter.",".mysql_errno().":".mysql_error()."!";
  }
}
if ($errorFlag == 0 && mysql_num_rows($result) > 0) {
  while(errorFlag == 0 && $row = mysql_fetch_array($result)) {
    if ($row['Last_Update_Alarm'] == 0) {
      $sql = "UPDATE $tbl_name SET Last_Update_Alarm='1', Status_Time='0' WHERE Machine_ID='$row[Machine_ID]'";
      $counter = 0;
      $result = 0;
      while ($result == 0  && $errorFlag == 0) {
        $result = mysql_query($sql);
        $counter = $counter + 1;
        if ($counter > 30) {
          $errorFlag = 1;
        }
      }
    }
  }
}

Error:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in D:...\test.php on line 33

Line 33 corresponds to the "while(errorFlag == 0 && $row = mysql_fetch_array($result)) {" line in the code segment.

Thanks,
Scott

Is this Arduino code? I don't think so.

$result will equate to false if there is no recordset. So, the simple answer is to enclose the second part of your code in a

if($result) {
if ($errorFlag == 0 && mysql_num_rows($result) > 0) {
  while(errorFlag == 0 && $row = mysql_fetch_array($result)) {
    if ($row['Last_Update_Alarm'] == 0) {
      $sql = "UPDATE $tbl_name SET Last_Update_Alarm='1', Status_Time='0' WHERE Machine_ID='$row[Machine_ID]'";
      $counter = 0;
      $result = 0;
      while ($result == 0  && $errorFlag == 0) {
        $result = mysql_query($sql);
        $counter = $counter + 1;
        if ($counter > 30) {
          $errorFlag = 1;
        }
      }
    }
  }

(Check the bracket pairs please!)