I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}
Related
I am using the following code to grab my mysql table rows and column headers without knowing them beforehand and formatting the table. I am creating a service that allows users to generate tables and save them into a mysql database so I need to be able to retrieve the data this way.
I am trying to update and edit he table and make it live. Usually this is done with each value being updated individually knowing all the column values.
This is my code to get the values
<?php
try {
$con= new PDO('mysql:host=localhost;dbname=xxx', "", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM ``
//first pass just gets the column names
print "<table>";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
I am trying to use the following to update the values:
foreach($_POST as $name=>$value)
{
if($value != '')
{
echo "$name: $value\n";
}
}
However, the row values are not updating at all. Is there any way I can scan the table and update the values each time a value is edited?
You don't need to perform the query twice. You can use the columnCount() and getColumnMeta() methods to get all the column names.
$result = $con->query($query);
$colCount = $result->columnCount();
echo "<tr>";
for ($i = 0; $i < colCount; $i++) {
$name = $result->getColumnMeta()["name"];
echo "<th>$name</th>";
}
echo "</tr>";
I have a table with the rows but for some reason it populates only 14 rows. I have around 800 rows in the db. Any ideas?
code:
$result = mysqli_query($con,"SELECT * FROM translation ORDER BY id");
while($row = mysqli_fetch_row($result) and $property = mysqli_fetch_field($result))
{
echo "<tr>";
foreach($row as $column => $value) {
// $column is column name 'englsih', 'spanish' etc.
$name = $property->name;
echo "<td align='left' class='cell".$column."'>". $value . "</td>";
}
echo "<td><span class='edit_b'></span><span class='remove_b'></span></td></tr>";
}
echo "</thead></table>";
I assume your translation table has 14 columns?
The problem is this:
... and $property = mysqli_fetch_field($result) )
You are fetching information about the columns in your result-set - and not even using it - and as soon as you have passed the last column, this will return false and your loop will end.
Don't fetch information about the columns in the same loop as your main results loop.
This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
I am attempting to retrieve the column headers for html headers from a MySQL query. The structure of my application is such that the column headers aren't static (sometimes there are 4, sometimes 7, etc.) For some unbearable reason I can't find a simple way to get the column names from any given query.
My end goal is to output an html table from the query.
Well if you get the query as an associative array, you can do something like this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($results)) {
if ($i < 1) {
foreach($row as $key => $val) {
echo $key;//column name
}
}
//Do other stuff
$i++;
}
And yes, I know they should be doing mysqli_..., but this is my example using old mysql_...
Edit
To expand on this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
echo "<table>";
while ($row = mysql_fetch_assoc($results)) {
echo "<tr>";
if ($i < 1) {
foreach($row as $key => $val) {
echo "<td>".$key."</td>";//column name
}
}
echo "</tr>";
echo "<tr>";
foreach($row as $key => $val) {
echo "<td>".$val."</td>";//column name
}
echo "</tr>";
//Do other stuff
$i++;
}
You can use function mysql_list_fields for getting column names.
Code below gets data from sql. Including header column
// Data, depends on your sql statement
$sql_dt = array(); // make sure it is array
foreach( $sql_dt as $key => $val ) {
$data[] = <<< EOH
<tr>
<th>$val['column_name']</th> <tr/>
<th>$val['column_age']</th>
<tr/>
EOH;
}
$table_dt = implode( $data );
echo <<< EOT
<table>
<tr>
<th>Name</th> <tr/>
<th>Age</th>
<tr/>
{$table_dt}
<table/>
EOT;
Here is my problem. I am returning results from a mysql database and using a for loop to echo the results. Though its getting a little complicated because I am using some table data to nest inside other results. This code returns "Pablo Picasso" inside a div called "Spain", fine, but if there is "El Greco" in Spain too, then I get two "Spain" divs, rather than just the one.
So: I'd like to only return a result once for each unique value in a table column, rather than for every one.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
foreach ($results as $row)
{
echo "<div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
$tempCountry = $row['country'];
foreach ($results as $row)
{
if ($row['country']== $tempCountry) echo "<div>artists name</div>";
}
echo "</div>";echo "</div>";
}
I'm wondering if it is the construction of the nested loop, or something else, I don't know!!! Please help
I agree with #Kalpesh that you need to order the results by country.
Right now you have multiple nested loops when all you really should need is one. Try using just one loop to go through the data. On every iteration, check the $tempCountry value to see if it different compared to the current row's country. If it is, you need to close the current <div>, open a new <div> and update the $tempCountry value. Otherwise, echo the name of the artist.
EDIT: Psuedocode added below
Retrieve data from database (the query should sort the data by country)
Initialize $tempCountry to null
Loop over every row
If $tempCountry equals this row's country
Print the artist
Else
Set $tempCountry equal to this row's Country
Close the div tag
Open a new div tag
Print the artist
Note that you do not want to close the div tag on the first time through the loop. Also, you need to close the div tag after the loop finishes.
foreach ($results as $row) {
if ($tempCountry == $row['country']) {
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
else {
$tempCountry == $row['country'];
echo "</div><div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
echo "</div>";
}
Create an empty array outside of your loop. On output push the values of $row into the array inside of your loop. Then only output if value does not already exist in the array. You can use in_array for this.
The solution I found was to nest a foreach inside another, the outer loop SELECTS with a GROUP BY.
In this example I get one outer for each country, then inside that , every person (or item) within that country (or with that column value). Really useful.
NEW CODE: SOLUTION (use GROUP BY to build outer container)
// create array to build group div
$country = mysql_query("SELECT * FROM table GROUP BY `country`");
// create array for inner contents
$result = mysql_query("SELECT * FROM table ORDER BY name");
//array for group(countries in this instance)
$countrys = array();
while ($row = mysql_fetch_assoc($country)) {
$countrys[] = $row;
}
//array for inner contents
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
$tempCountry="";
foreach ($countrys as $row)
{
$tempCountry = $row['country'];
echo "<div class=\"".$row['country']."\">";
echo $row['country'];
echo "<div class=\"Box\">";
foreach ($results as $row) {
if ($tempCountry == $row['country'])
{
echo"<div>inner contents of that group</div>";
}
}
echo "</div>";
echo "</div>";
}
I have a query which retrives two colums of multiple rows from the db.I want it to display this in a table using php,I have to use two dimensional arrays i guess.Please help on how shall i proceed.
while($row=mysql_fetchrow_array($qry))
{
Please guide how to store the columns in the array[][]
}
[Please guide on how to display the result in the display page]
foreach( )
{
}
// store the columns in the array[][]:
$res = array();
while($row=mysql_fetch_array($qry, MYSQL_NUM)) {
$res[] = $row;
}
// display the result in the display page
echo "<table>\n";
foreach($res as $row) {
echo "<tr>\n";
foreach ($row as $fld) {
echo "<td>$fld</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";