Search code examples
phppostgresqljpgraph

Setting database field based conditions in PHP/Postgresql WHILE loops


I've got a partial solution but am stumped on how to best set conditions based on record fields, within a while loop? I've tried "IF" but got further with switch/case. I am using jpgraph with PHP / Postgresql and have set up a switch to format gantt bars according to a record type field "rectype". In my test code, "rectype" can be either "NORMAL" or "GROUP". The query does output all 7 records in the table (tested with pgadmin3) but the gantt chart only outputs the first 6 of the 7 table records and the bar formatting is applied to the previous record - in my test case, record 4 has the "rectype" field set to "GROUP", but the "GROUP" formatting is applied to record 3.

$sql = "SELECT activity, start, due, rectype, title, FROM activity LEFT JOIN project ON activity_projectid = projectid ORDER BY activity_projectid, start";
$result = pg_query($sql);

// Add data to gantt
$i = 0;
while($act = pg_fetch_assoc($result)) {
 $type = pg_fetch_result($result,"rectype");
 switch($type) {  
 case "GROUP":  
    $data = new GanttBar ($i,array($act['activity'],$act['title']),$act['start'],$act['due']);
    $data->SetPattern(BAND_SOLID,'black');
 break;  
 case "NORMAL":  
    $data = new GanttBar ($i,array($act['activity'],$act['title']),$act['start'],$act['due']);
    $data->SetPattern(BAND_RDIAG,'red');
 break;
 }
$graph->Add($data);
$i++;
}

Solution

  • You can't mix pg_fetch_assoc with pg_fetch_result. You should use:

    while($act = pg_fetch_assoc($result)) {
        $type = $act['rectype'];