m4773rz
m4773rz

Reputation: 55

Nested While Loops php

I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.

I have gotten the code to work but it keeps displaying:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

I have tried every way possible I have found online to help, but none work.

$resulta = mysql_query("SELECT dbname AF012 FROM Customer");

while($data = mysql_fetch_array($resulta))
  {
    $db = $data[' dbname '];

$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
  {
    //checking if any record is 1,2 or 3
  if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) )          {
      //if any match the if adding 1 to the counter
      $counter ++;
    }
     }
 unset($result2);
echo $db."  ".$counter;
 echo "<br>";
 $counter = 0;
 $result = null;
 $result2 = null;
}

All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.

Upvotes: 3

Views: 9615

Answers (2)

hakre
hakre

Reputation: 197777

You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:

function mysql_query_array($query)
{
    if (!$result = mysql_query($query)) {
        throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
    }
    return function () use ($result) {
        return mysql_fetch_array($result);
    };
}

With that little helper function, your code is now more compact and it has actual error handling:

$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
    $counter = 0;
    $queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
    while ($row = $queryB())
    {
        if (in_array($row['changemade'], range(1, 3))) {
            $counter++;
        }
    }
    printf("%s  %s<br>\n", $db, $counter);
}

Upvotes: 4

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];

Upvotes: 1

Related Questions