anders
anders

Reputation: 1545

php while loops not executing properly

I have three wards A,B,C in my database and 4 Employees (3 on ward A, 4 on B and 1 on C) and the below script prints out all the Wards correctly and prints out the 3 employees that works on ward A but nothing more (I:E it only compares against ward A and not the other 2) See Image

Can you see any obvious error in the order that the php is executing that causes this? I'm new to PHP so thats why I don't quite understand the syntax =)

while ( $row = mysql_fetch_array($wardNames) ) {

        echo("<tr><td><a href=\"javascript:displayWard('" . $row['Name'] ."')\">
        <div class='wardHeader'><div class='plus'></div><div class='wardName'><b>" . $row['Name'] . " </b></div>
        </div>
        </a></td></tr>");

        while ( $employeerow = mysql_fetch_array($Employees)) {//Only prints out employees on ward A and not B or C. Why?
            if($employeerow['Ward']==$row['Name']){
                echo("<tr><td>" . $employeerow['Name'] . "</td></tr>"); 
            }
        }
    }

Upvotes: 0

Views: 86

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318808

After iterating over a resultset it's exhausted and thus not iterable anymore. Store it in an array before the outer loop:

$all_employees = array();
while($row = mysql_fetch_array($Employees)) {
    $all_employees[] = $row;
}

while ( $row = mysql_fetch_array($wardNames) ) {

    echo("<tr><td><a href=\"javascript:displayWard('" . $row['Name'] ."')\">
          <div class='wardHeader'><div class='plus'></div><div class='wardName'><b>" . $row['Name'] . " </b></div>
          </div>
          </a></td></tr>");

    foreach($all_employees as $employeerow)
        if($employeerow['Ward']==$row['Name']){
            echo("<tr><td>" . $employeerow['Name'] . "</td></tr>"); 
        }
    }
}

Upvotes: 1

Related Questions