Is it possible to dynamically build a table using PHP? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
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);
}

<?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) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
First example on: http://www.php.net/manual/en/function.oci-execute.php

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).

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;
}

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...

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.

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);

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;

Related

Display PHP Query results in table regardless of # of columns returned?

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?
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);

How to xml to php nested arrays?

I 'm a total PHP beginner and need some help :-)
Have this xml:
http://pastebin.com/ZSpNPhXH
And this scrypt:
<?php
// Retrieve XML File
$file = file_get_contents('livescore-feed.xml');
// Parse XML with SimpleXML
$livescore_data = new SimpleXMLElement($file);
foreach ($livescore_data->league as $league) {
echo "<table class='table table-striped table-bordered table-condensed'>";
echo "<thead><tr><th colspan='6' id='league'>" . $league->attributes()->name . "</th></tr></thead>";
echo "<tbody>";
foreach ($league->match as $match) {
$status = $match->attributes()->status;
$home = $match->home->attributes()->name;
$away = $match->away->attributes()->name;
$score = $match->home->attributes()->goals . " - " . $match->away->attributes()->goals;
// If match not yet started, there will be a ":" in 'status' attribute
if (strpos($match->attributes()->status,':') !== false) {
$score = "-";
}
echo "<tr><td class='status' id='match'>" . $status . "</td><td id='match' colspan='2'>" .
$home . "</td><td class='score' id='match'>" . $score . "</td><td id='match' colspan='2'>" .
$away . "</td>
</tr>";
}
echo "</tbody></table>";
}
?>
How to show/parse "events" also
Thank you very much for your help and suggestions
In the same way you parse other data!
foreach( $livescore_data->league as $league )
{
(...)
foreach( $league->match as $match )
{
(...)
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
foreach( $match->events->event as $event )
{
echo $event['assist'] . '<br>';
echo $event['player'] . '<br>';
(...)
}
}
}
You have to perform a loop through $match->events->event and you can get each <event> attribute using $event[attribute] syntax. So, $event['extra_min'], $event['minute'], etc...
You have only to adapt the code to your table structure.

Add links to data in HTML table Created using PHP and a MYSQL database

I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";

why does foreach skip 2 rows from the query result?

For 10 rows in the query it only returns 8 rows but i get the fields right:
For Query data which returns less than 2 rows I get an error.
//create table to display all data
echo "<table border="1"> ";
echo "<tr>";
$row = mysqli_fetch_assoc($result);
foreach($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
while (($row = $result->fetch_assoc()) !== null)
{
$output = array();
$i=1;
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[] = $columnName."=>". $columnValue;
echo "<td>".$columnValue."</td>";
}
echo "</tr>";
}
echo "</table>";
Edit: Thanks to #Michael Berkowski for his comments on the question.
Here is a modified version of your code that should work:
//create table to display all data
echo "<table border=1 >";
echo "<tr>";
//echo "<th> ## </th>";
$row = $result->fetch_assoc(); // stick to the object-oriented form. It is cleaner.
foreach ($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
do
{
$output = array();
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[$columnName] = $columnValue; // this is neater.
echo "<td>" . $columnValue . "</td>";
}
echo "</tr>";
} while ($row = $result->fetch_assoc());
echo "</table>";
You can use your first foreach() loop to print the keys and then use a do-while() loop to get your desired output.
Additional reading:
PHP do-while loop
You need to use
mysqli_fetch_assoc($result);

Populate an html table columwise with mysql data

I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>

Categories