Rendering data into a graph
Look at the code below. I haven't tried it yet, but the idea is avoid iterating query that will take a long time. So, I just use one query.

CASE "TestGrid":
        $SnapArrayResult = array();
        $PlayArrayResult = array('A','B','C','D');
        echo "&lt;table id='tb' style='width:200px;height:200px;font-family:tahoma;font-size:2pt;visibility:hidden;' cellspacing='0'&gt;\n";
        echo "&lt;caption&gt;Data on Alliance&lt;/caption&gt;\n";
        echo "&lt;thead&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;\n";
        $SnapResult = $db-&gt; query("SELECT snap,COALESCE(count(*),0) as pCnt,hex(alliance) as alliance FROM scSVR WHERE hex(alliance) IN (hex('A'),hex('B'),hex('C'),hex('D')) GROUP BY snap,alliance ORDER BY snap ASC");
        $changeSnap = null;
        $PlayerRow = array();
        while ($SnapRow = $db-&gt; fetch_assoc($SnapResult))
        {
            if($changeSnap!=$SnapRow['snap'])
            {
                $SnapArrayResult[] = $SnapRow['snap'];
                $changeSnap=$SnapRow['snap'];
                $PlayerRow[$changeSnap] = array();
                echo "&lt;th&gt;".DTConvS($SAR)."&lt;/th&gt;\n";
            }
            $PlayerRow[$changeSnap][$SnapRow['alliance']] = $SnapRow['pCnt'];
        }

        echo "&lt;/tr&gt;&lt;/thead&gt;\n";
        echo "&lt;tbody&gt;";
        foreach($PlayArrayResult as $PAR){
            echo "&lt;tr&gt;&lt;th scope='row'&gt;".$PAR."&lt;/th&gt;";
            foreach($SnapArrayResult as $SAR){  
                echo "&lt;td&gt;".$PlayerRow[$SAR][$PAR]."&lt;/td&gt;\n";
            }
            echo "&lt;/tr&gt;";
        }
        echo "&lt;/tbody&gt;&lt;/table&gt;";
        break;