Reputation: 19
Help me, i got stack when i want to make a dynamic table,
so the idea of the program is we can be costume a select field of database and can show it. so if we have this field on table in database :
Address
and we just want to show Name and Address, so i save the rule on the database (SELECT Name, Address)
but the problem is on the dynamic table when i show, how to make dynamic table when field always change (Example :Maybe the field just Age, or Name and age or we show all #its just from Configure that i make)
i have tried to make query result into an array and show it like this.
<table>
<?php for($x=0;$x<$length_array;$x++){ ?>
<tr>
<?php for($y=0;$y<$width_array;$y++){ ?>
<td><?php $result[$length_array][$width_array] ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
note : variable $result is from result query and i change it into an array, but the problem is i cann't count a length and width from array in this code.
Upvotes: 0
Views: 64
Reputation: 3586
It depends a bit on how your result set is returned, but based on your code above I'll assume your result is an array of arrays.
First think about what you want: you want an html table with a header that gives the name for each column, and then has a row for each record in your result set.
I very much dislike mixing php and html, so I will use a different syntax style, but the steps are the same no matter what style you use. This way makes the logic a lot easer to read.
First, make the table.
<?php
$html = '<table>';
Now you want to add a header to the table and create a cell for each column in your result. Before you do that, you need to answer: where are you going to get the names for you columns? There are two possible answers; 1) directly from the results of your query, or 2) hard-code them.
Getting them directly from the query results is much more flexible, but the names you give your database columns may not always be human-friendly.
$columnNames = ['Name', 'Address'];
---- OR ----
$firstRow = $result[0]; // of course we have checked that the result set is not empty!
$columnNames = array_keys($firstRow); // adjust if rows are objects instead of arrays
Now output the header:
$html .= '<thead>';
foreach($columnNames as $columnName) {
$html .= '<th>' . $columnName . '</th>';
}
$html .= '</thead>';
Now we can move on to the body, as in the answer to your previous question, creating a row in the table for each item in your result set. For each row you have an inner loop that creates the markup for each cell.
$html .= '<tbody>';
foreach($result as $row) {
$html .= '<tr>';
foreach($row as $cell) {
$html .= '<td>' . $cell . '</td>';
}
$html .= '</tr>';
}
$html .= '</tbody>';
$html .= '</table>';
print $html;
Upvotes: 1