1

So I'm exploring the wonderful world of PHP and I'm still creating very dirty, poorly build code but I'm trying to get better! So my question is as follows:

Is there a way to automatically calculate the columns in the result set and spit out a pretty HTML table regardless of query used?

Here the current code:

<?php
include '../includes/connect.php';
include '../includes/queries.php';
$stid = oci_parse($conn, $export);
oci_execute($stid);
echo "<table class='pure-table pure-table-striped' style='font-size:11px;'><thead><tr><th>Name</th><th>File Name</th><th>Export Date</th></tr></thead>";
while (oci_fetch($stid)) {
    echo "<tr><td>" . oci_result($stid, 'DISPLAY_NAME') . "</td>";
    echo "<td>" . oci_result($stid, 'LAST_EXPORT_FILE') . "</td>";
    echo "<td>" . oci_result($stid, 'LAST_EXPORT_DATE') . "</td></tr>";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);

I'd like to use the same table every time, but just have it auto detect column header names and number of columns and return it in a table.

Is it possible or does it make sense?

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
Birkley
  • 183
  • 1
  • 13

1 Answers1

0

I do exactly that using PDO.

$out = '';
$q = $conn->prepare($SQL);
if ($q->execute()) {
    $rows = $q->fetchAll();
    if (!empty($rows)) {
        //We have something
        $out .= "<table class='pure-table pure-table-striped' style='font-size:11px;'>";
        $first = true;
        //iterate on rows
        foreach($rows as $row) {
            //Clean out all the numeric keys - stops duplicate values
            foreach ($row as $key => $value) {
                if (is_int($key)) {
                    unset($row[$key]);
                }
            }

            //header
            if ($first) {
                //write header
                $out .= '<thead><tr>';
                foreach ($row as $key => $value) {
                    $out .= '<th>' . $key . '</th>';
                }
                $out .= '</tr></thead>';
                $first = false;
            }
            //write line
            $out .= '<tr>';
            foreach($row as $key => $value) {
                $out .= '<td>' . $value . '</td>';
            }
            $out .= '</tr>';
        }
        $out .= '</table>';
    }
}
echo ($out);
Nico Westerdale
  • 2,147
  • 1
  • 24
  • 31
  • Thanks for the quick response! I'll test this before EOD and let you know how it turns out. – Birkley Nov 02 '16 at 15:15
  • 1
    You should use `$q->fetchAll(\PDO::FETCH_ASSOC);` to make PDO return only associative indices and then you don't waste execution time removing the numeric indices. – timclutton Nov 03 '16 at 12:57