Category Archives: snippets

PHP Output Table with Where Condition

Simple PHP code snippet to output table with where condition, outputs table headings, and fields as rows in a HTML table.

  //OUTPUT TABLE
  function output_table($tablename,$condition="")
  {
    //PRINT FIELD PROPERTIES FROM DATABASE
    $sql = "SHOW COLUMNS FROM tablename";
    $headings = $this->execute_query($sql);
    // echo "<pre>";
    // print_r($headings);
    // echo "</pre>";
    // foreach($headings as $i => $value) {
    //    echo $value["Field"];
    // }

    $sql = "SELECT * FROM ".$tablename . ' ' . $condition; // WHERE id = '{$category}'";
    $table = $this->execute_query($sql);

    echo '<table>';
    foreach($headings as $i => $value) {
       echo '<th>' . $value["Field"] . '</th>';
    }
    foreach ($table as $row) {
        echo '<tr>';
        foreach ($row as $field) {
            echo '<td>'.$field.'</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
  }