dynamic table base on database field - php

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 :
No
Name
age
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.

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;

Related

PHP display data in table using foreach loop

I have the 2020 hurricane name and all the states. I want to loop through my database and see if the options are picked. If they are, populate the spot with the name. If not, add"--". It will look almost like a spreadsheet of data.
When I submit data, it doesn't populate in the right spot and add a bunch of empty cells.
This is my queries:
// DB Connection
$db_connection = mysqli_connect('localhost','root','','hurricane_bowl');
$i = "SELECT * FROM users RIGHT JOIN states USING (state_id) GROUP BY (state_name) ORDER BY state_name ASC";
$state = mysqli_query($db_connection, $i);
$g = "SELECT * FROM users RIGHT JOIN hurricanes USING (hurricane_id) GROUP BY (hurricane_name) ORDER BY hurricane_name ASC";
$hurricane = mysqli_query($db_connection, $g);
This is my loops:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">Hurricane Name</th>
<?php
foreach($state as $stval) {
echo '<th scope="col">' . $stval['state_name'] . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($hurricane as $h) {
echo '<tr>';
echo '<th scope="row">' . $h['hurricane_name'] . '</th>';
foreach($state as $st) {
if($st['state_id'] != NULL && $h['hurricane_id'] != NULL) {
echo '<td>' . $st['username'] . '</td>';
} else {
echo '<td>--</td>';
}
}
echo '</tr>';
}
?>
</tbody>
</table>
The first change needs to be to the queries: if you want to display three separate query results, you need three separate tables, otherwise it makes not sense because there is no connection between the three datasets you are retrieving. Alternatively, you need just one dataset. Use JOIN in a query to link multiple table results, assuming there is a link between the tables.
W3Schools on this topic: https://www.w3schools.com/sql/sql_join.asp
Secondly, when loops are nested, each layer is its own dimension. In your case, you are trying to create a sort of 3-dimensional table, which can't work. Typically for a query result you only need one foreach loop, but if you don't have any information on the table fields, you can have two, not more.

get column names from stored procedure for displaying in html table using php

I am trying to display html table from a stored procedure using PDO.Resultset contains lot of columns and rows which needs to be exported to an excel.
But I need to get the column names to be on the first row, how can be possible on the below code? Any help ?
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
foreach ($arrValues as $key=>$value)
{
$column_names[]=$key;
?>
<td><?=$value?></td>
<?
}
echo "</tr>";
}
The below code displays the column name, but I want it to be the top row of the table.
echo "<tr>";
foreach ($column_names as $name)
{ ?>
<td>
<?=$name?>
</td>
<?
}
echo "</tr>";
?>
The question has nothing to do with stored procedures, as it's applicable to any data returned from database.
the most convenient way would be to fetch the data first, get the column names from the first row and then print the data.
besides, use of prepare execute is not justified for this query
$data = $db->query( "CALL spalldetails" )->fetchAll(PDO::FETCH_ASSOC);
$column_names = array_keys($data[0]);
here you have your column names before output which you can make using foreach() instead of while()
I would suggest instead of printing the output immediately while processing the through the for loop, you rather create a string to output later. This can be accomplished simply like this: (mind you the below is untested air code, but to show you an example of what I mean)
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
$tablestring .= "<tr>";
foreach ($arrValues as $key=>$value){
$column_names[]=$key;
$tablestring .= "<td>".$value."</td>";
}
$tablestring .= "</tr>";
}
$headstring .= "<tr>";
foreach ($column_names as $name)
{ $headstring .= "<td>".$name."</td>";
}
$headstring .= "</tr>";
echo "<table>".$headstring.$tablestring."</table>";

Creating a HTML table with MYSQL fetching data doesn't work

I'm attempting to create a dynamic table with MYSQL's function: while(mysql_fetch_assoc).. However, when it fetches more than one result, it doesn't create the table anymore (or fill in the tags. Excuse me for explaining this incorrectly)
This is my code. Ignore the Dutch words :)
$sql2 = mysql_query("SELECT * FROM kostendb WHERE ProjectID = '$_GET[id]'") or die (mysql_error());
echo '
<table border="1" style="width:60%">
<tr>
<th>Kostencode</th>
<th>Datum</th>
<th>Bedrag</th>
</tr>';
while($res = mysql_fetch_assoc($sql2))
{
echo '<tr>';
echo '<td>' .$res['KostenID']. '</td>';
echo '<td>' .$res['Datum']. '</td>';
echo '<td>' .$res['Bedrag']. '</td>';
echo '</tr>';
}
echo '</table>';
When it finds more than one result, the while-loop doesn't do anything. When it finds just one result, it works fine.
What is causing this, and how can I fix this?
I've checked out an example script, but it's exactly using my method.
Thanks
You might have mixed mysql with mysqli.
Choose one, don't mix and this might fix your problem.
make a variable like $project = $_GET['ID'];
then put in sql statement as ....WHERE Project_ID = $project");
Try this

php echo table with while loop

I am creating a table and want it laid out a certain way and have to retrieve the data from the DB. I am trying to get it set up where it has the usernames across the top example...
Jim Chris Allen Rick
7 8 4 5
my code looks like this and I have been messing around with it for hours and cant figure out why I cant get it set up how I want. Any help would be appreciated. Its a while loop.
while ($pickresults= mysql_fetch_assoc($picksquery)) {
//first row
echo '<th> '.$pickresults['username'].' </th> ';
echo ' <td> '.$pickresults['firstgame'].' </td> '; }
First off, you should learn the HTML code for tables. Your code is putting a Table Header (th) next to a normal column item (td). You need to loop through the headers first then next row loop through the column items or build the strings to echo out.
$headers = $col = "";
while($pickresults= mysql_fetch_assoc($picksquery)){
$headers .= "<th> {$pickresults['username']} </th>";
$col .= "<td> {$pickresults['firstgame']} </td>";
}
echo "<table><tr>$headers</tr><tr>$col</tr></table>";
Your structure is creating a TH then a TD and then a TH and then a TD etc.
This isn't how you create a table, you first need to make the four TH's and THEN you can make the four TD's.
Edit: Marko D has supplied the code to explain what I mean.
First collect table header and body, and then output them. The way you were doing, html was like this, I guess it's easy to see what is wrong with html
<th>name</th>
<td>value></td>
<th>another name</th>
<td>another value</td>
What you need is this:
$td = '';
$th = '';
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$th .= '<th> '.$pickresults['username'].' </th> ';
$td .= '<td> '.$pickresults['firstgame'].' </td> ';
}
echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>';
You need to write all usernames in <th>-tags.
I'd put it in an array first, and from the array into the table...
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$picked[]=$pickresults;
}
echo "<table><tr>"; // create table and 1st row
foreach ($picked as $pick) {
echo "<th>{$pick['username']}</th>"; // create 1st line headers
}
echo "</tr><tr>"; // close 1st row and open 2nd
foreach ($picked as $pick) {
echo "<td>{$pick['firstgame']}</td>"; // create 2nd line...
}
echo "</tr></table>"; // close 2nd row and table

Adding extra table row

I'm stuck and can't figure this out.
I have this piece of code which is basically generating a table taking data from SQL cursor.
I need to add one extra table row <tr> (which will be filled with additional info) after each row. I've tried putting the new row in several places, but there is never any output data for it. This is someone else's code that I'm trying to modify.
$top_i=min($pagesize-1,$numrows-$start);
for($i = 0;$i<=$top_i;$i++) {
if (($i%2)==1)
echo "<tr class='saraksts_row0'>";
else
echo "<tr class='saraksts_row1'>";
$res=mssql_query("fetch absolute ".($start+$i)." from saraksts_cursor ");
$row=mssql_fetch_array($res);
$itemp = 0;
foreach($fields as $field) {
$key = $field[0];
if($field[2]) {
eval($field[2] );
}
$itemp++;
$val = ($row[$key] == "") ? " " : $row[$key];
// Get rid of right and left border, set topmost border
$st="";
if ($itemp==1)
$st.="border-left-style:none;";
if ($itemp==$numfields)
$st.="border-right-style:none;";
if ($i==$top_i)
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
$itemp = 0;
echo "</tr>\n";
}
The place where you want to add the extra row is after closing the first row and before the iteration moves to the next one. Note, it appears that you are doing some styling based on whether the row is odd or even. If you want this new row to have the same styling, I suggest you store the class you're applying to the preceding row so that you can also apply it to this row.
echo "</tr>\n";
echo "<tr><td>...</td><td>...</td></tr>\n"; /* Add the new row here */
}
...
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
//Here we go
echo '<td style="blah">'.$yourotherinfo.'</td>';
$itemp = 0;
echo "</tr>\n";

Categories