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>';
?>
Related
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>";
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);
So i have a database with 33 column's
Now this is my query :
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
while ($result = $r3->fetchAll()){
foreach($result as $row3){
echo "<tr>";
echo "<td colspan='2'>Kill ".$row3['ID']."</td>";
echo "<td>".$row3['Dragon_Bones']."</td>";
echo "<td>".$row3['Royal_Dragonhide']."</td>";
echo "</tr>";
}
}
How can i make it so that i only need to have 1 $row3 and not need to write all the column names in it?
You can try fetch() and fetch associate instead of fetchAll. Try this.
while ($result = $r3->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
foreach($result as $value){
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
You can use a second foreach to traverse to array you get as follows:
while ($result = $r3->fetchAll())
{
foreach($result as $row3)
{
echo "<tr>";
foreach($row3 as $key=>$val)
{
echo $key;
echo $val;
}
echo "</tr>";
}
}
This will display the key (column name) and the value in it.
If you want to just display the values, you can use this instead:
while ($result = $r3->fetchAll())
{
foreach($result as $row3)
{
echo "<tr>";
foreach($row3 as $key=>$val)
{
echo $val;
}
echo "</tr>";
}
}
If you are just trying to put out a table of the rows, and want the headings on the first row then you can use mysqli_data_seek() to reset the pointer back to the start after processing the first row to get the titles.
Something like this (assuming you can use mysqli_fetch_assoc):-
<?php
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
if ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_key."</td>";
}
echo "</tr>";
$db1->data_seek(0);
while ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_value."</td>";
}
echo "</tr>";
}
}
?>
EDIT - if your db class doesn't support mysqli_data_seek() (or if you are using an unbuffered query):-
<?php
$q3 = "SELECT * FROM qbd";
$r3 = $db1->query($q3);
if ($result = $r3->fetch_assoc())
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_key."</td>";
}
echo "</tr>";
OutputRow($result);
while ($result = $r3->fetch_assoc())
{
OutputRow($result);
}
}
function OutputRow($result)
{
echo "<tr>";
foreach($result as $row3_key=>$row3_value)
{
echo "<td>".$row3_value."</td>";
}
echo "</tr>";
}
?>
$keys = array();
$values = array();
echo '<table>';
while ($result = $r3->fetchAll()){
foreach($result as $row3){
foreach($row3 as $key=>$val){
for($i=1;$i=30;$i++){
$keys[]=$key;
}
$values[] = $val;
}
echo '<tr>';
foreach($keys as $k){
echo $k;
}
foreach($values as $v){
echo $v;
}
echo '</tr>';
}
}
echo '</table>'
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"
I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;