phparrayspostgresqlloops

Dynamically access all column values of all rows in a query resultset


I'm trying to output query results into a <table> but I'm in a dilemma.

I know I can simply do:

while ($row = pg_fetch_assoc($query)) {
       echo "<td class='cell100'>" . $row['name'] . "</td>";
       echo "<td class='cell100'>" . $row['dynamic_col_1'] . "</td>";
       echo "<td class='cell100'>" . $row['dynamic_col_2'] . "</td>";
       echo "<td class='cell100'>" . $row['dynamic_col_3'] . "</td>";
       echo "<td class='cell100'>" . $row['dynamic_col_4'] . "</td>";
       echo "<td class='cell100'>" . $row['dynamic_col_5'] . "</td>";
}

The problem is depending on the user's settings - 'dynamic_col_1' to 'dynamic_col_X' will not necessarily appear in that order neither necessarily have that particular name.

I'd like to keep the user's defined order and dynamic column names as already sorted from the query.

How can I achieve this without using the column names - $row['dynamic_col_X'] seeing as it changes from one user to the next? Is there a way to use array keys or something similar?


Solution

  • You could try a foreach, looping over the columns, and then tweak to suit whatever you're doing:

    foreach ($row as $column => $value) {
        echo $column . ' ' . $value;
    }