0

Is it possible to dynamically build a table using PHP?

I am using code such as the below to build tables etc. but as there are multiple I was wondering in this case is it possible for the table to be built dynamically based on the SQL query?

For example if I need to build another table then I can copy the below code and just edit the SQL rather than also editing the column headers etc. in the HTML.

Basically some method to simplify the below code so that it is more compact\tidier if being used multiple times on the same page.

Code

  <?php

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

  include('core/connection.php');

  if($conn){

  $stid = oci_parse($conn, "

    SELECT *
    FROM
    (
      SELECT c1, c2, c3, c4
      FROM t1
      ORDER BY c1
    )
    WHERE ROWNUM <= 10

  ");
  oci_execute($stid);

  echo "<table class='table table-hover '>
        <thread>
        <tr>
        <th>c1</th>
        <th>c2</th>
        <th>c3</th>
        <th>c4</th>
        </tr>
        </thread>
        <tbody>";

  while ($row = oci_fetch_array($stid, OCI_NUM)) {

    echo "<tr>";
    echo "<td>" . $row['0'] . "</td>";
    echo "<td>" . $row['1'] . "</td>";
    echo "<td>" . $row['2'] . "</td>";
    echo "<td>" . $row['3'] . "</td>";
    echo "</tr>";
    unset($row);

  }

  echo "</tbody>
        </table>";

  oci_free_statement($stid);
  oci_close($conn);

  }
1
  • 1
    Create a tablify class or function? something like tablify($headings, $rows); ? It really depends on how complex you want to go... May 12, 2014 at 14:52

7 Answers 7

1
<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

First example on: http://www.php.net/manual/en/function.oci-execute.php

0

You could use something like jQuery DataTables, http://datatables.net/ - it will allow you build the table from a JSON-object that you have made with PHP (i.e. by using json_encode() on your SQL result).

0

Here's my 2 cents on it:

function DisplayRawDataset( $dataset, $connection) {


    $res = !is_resource($dataset) ? mysqli_quert($dataset) : $dataset;

    if ( !is_resource($res) ) return  '';

    $i = 0;
    $retstr = "";
    $retstr .= "<table" border=\"1\" style=\"border-collapse:collapse;\" cellspacing=\"0\" cellpadding=\"2\" >";
    while($row = $res->fetch_assoc()){

        if($i == 0){
            reset($row);
            $retstr .= "<tr>";
            while(list($key, $val) = each($row)){
                $retstr .= "<th><b>".htmlspecialchars($key)."</b></th>";
            }
            $retstr .= "</tr>";
        }
        $retstr .= "<tr>";
        reset($row);
        while(list($key, $val) = each($row)){
            $retstr .= "<td>".htmlspecialchars($val)."</td>";
        }
        $retstr .= "</tr>";
        $i++;
    }
    $retstr .= "</table>";
    return $retstr;
}
0

U could probably do this

$return = "<table class='table table-hover '>
        <thread>
        <tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key){
$return .= "
        <th>".$key."</th>
";

}
$return .= "
</tr>
        </thread>
        <tbody>
<tr>";

foreach(oci_fetch_array($stid, OCI_NUM) as $key => $value) {


    $return .= "<td>" . $value . "</td>";


  }


$return .= "</tr>
</tbody>
            </table>";
}

echo $return;

or something along this line...

0

I use this....

<?php
/**
    @file:      tableFunctions.php
    @version:   1.0


*/
//Initialize $headersPrinted boolean
$headersPrinted = false;

function obj2Table($obj, $id, $loop)//Passed arguments should include the object, the id for the created table, and '1' for the default first loop
{
    global $headersPrinted;
    $print = false; 
    if ($loop == 1)
    {
        //Setup a table to output the object
        echo "<table id=\"$id\" border='.5'>\r\n";
    }
    //Loop through the object
    foreach ($obj as $name => $value) 
    {       
        //Check for nested objects
        if (is_object($value))
        {
            //If it is a nested object, feed the child back through
            obj2Table($value, $id, 0);
        }//end if(is_object)
        //Check for nested arrays
        elseif (is_array($value))
        {
            //If it is a nested array, try to feed each array back through
            foreach ($value as $arrayKey => $arrayValue)
            {
                obj2Table($arrayValue, $id, 0);
            }       
        }//end elseif(is_array)
        else
        {
            //Set the $print boolean to true to print the rows once the foreach ends            
            $print = true;
            if (!$headersPrinted)
            {
                $keys[] = $name;                
            }
            $cells[] = $value;                      
        }//end else
    }//end foreach  
    if ($print)
    {       
        if (!$headersPrinted)
        {
            echo "<tr>\r\n";
            foreach ($keys as $key)
            {
                echo "<th>$key</th>\r\n";
            }
            echo "</tr>\r\n";
            $headersPrinted = true;         
        }           
        foreach ($cells as $cell)
        {
            echo "<td>$cell</td>\r\n";  
        }
        echo "</tr>\r\n";
    }   
    if ($loop == 1)
    {
        //Close the table
        echo "</table>\r\n";
        //Set the $headersPrinted boolean back to false
        $headersPrinted = false;
    }//end if(initialLoop)
}//end function obj2Table() 

?>

The just include that file in your php. In your while statement for the query results, just add each row to an array like this.. $results[] = $row;. After the while loop, then send the results to the function like this... obj2Table($results, 'queryTable', 1);. NOTE: you would need to change your oci_fetch_array to oci_fetch_object.

0

You can do something like this...

$sql = "SELECT field1 as 'Colunm 1', field2 as 'Colunm 2', fieldn as 'Colunm n' FROM table;";

function buildTable($sql){
    $tab = "";
    $head = "";
    $body = "";
    if (is_string($sql) && $sql !== "") {
        $qry = mysql_query($sql);
        while ($fet = mysql_fetch_assoc($qry)) {
            if ($head == "") {
                $head = "<tr>";
                foreach ($fet as $key => $val) {
                    $head .= "<th>{$key}</th>";
                }
                $head .= "<tr>";
            }
            $body .= "<tr>";
            foreach ($fet as $key => $val) {
                $body .= "<td>{$val}</td>";
            }
            $body .= "</tr>";
        }

        return "<table><thead>{$head}</thead><tbody>{$body}</tbody></table>";
    }
}

echo buildTable($sql);
0

Yes , it is possible , but you are doing it wrong. HTML that you echo is not valid (some HTML elements have a required closing tag like <table></table> so you should output <table> and </table> in one echo). One of the options for you is to assign your dynamic HTML to a value and then echo the valid HTML.

$buffer = "<table class='table table-hover '>
           <thread>
              <tr>
                 <th>c1</th>
                 <th>c2</th>
                 <th>c3</th>
                 <th>c4</th>
              </tr>
           </thread>
           <tbody>";

while ($row = oci_fetch_array($stid, OCI_NUM)) {
   $buffer .= "<tr>
                 <td>" . $row['0'] . "</td>
                 <td>" . $row['1'] . "</td>
                 <td>" . $row['2'] . "</td>
                 <td>" . $row['3'] . "</td>
               </tr>";
   unset($row);
}

$buffer .=  "</tbody>
             </table>";
echo $buffer;

Not the answer you're looking for? Browse other questions tagged or ask your own question.