why does foreach skip 2 rows from the query result? - php

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

Related

Get each array item from foreach loop as table data

I'm trying a foreach loop on an array with 20 names. I should derive a table with 4 columns and 5 rows, with each cell(table data) having a unique name. My code is below with a snapshot of the output table. It hasn't worked just yet. How can I fix this?
<?php
$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i");
echo "<table width='200' border='1' >";
foreach($names as $name){
echo "<tr>";
for($cols=1;$cols<5;$cols++){
echo "<td>".$name."</td>";
}
echo "<tr>";
}
echo "<table>";
?>
1st : Remove for loop
2nd : apply the limit using $i
Note 1 : Your looping single name 5 times .that should not .
Note 2 : for more detail read my comment lines .
<?php
$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i");
echo "<table width='200' border='1' >";
$i=0;
foreach($names as $name){
if($i==0){ //open new tr if $i is 0
echo "<tr>";
}
echo "<td>".$name."</td>";
if($i==3){ //close the tr if the $i is reached the 3 .
echo "</tr>";
$i=-1; //why setting -1 means i'm incrementing after this so i set -1
}
$i++;
}
echo "<table>";
?>
Splitting the array into chunks of the wanted size may make for more readable code:
$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i");
echo "<table width='200' border='1' >";
$names = array_chunk($names, 4);
foreach($names as $group){
echo "<tr>";
foreach($group as $name) {
echo "<td>".$name."</td>";
}
echo "</tr>";
}
echo "<table>";

Single php array to html table

The idea is to print an html table from this array:
$arr = ['1','2','3','4,'5,'6','7','8','9'];
I expect my table to be something like:
1 2 3
4 5 6
7 8 9
I tried a lot but I couldn't find an idea to do this.
My idea was to break each three element but I need something smarter.
You can use array-chunk like this:
$arr = ['1','2','3','4','5','6','7','8','9'];
echo "<table>";
foreach(array_chunk($arr, 3) as $row) {
echo "<tr>";
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>";
}
echo "</table>";
$arr = ['1','2','3','4','5','6','7','8','9'];
$from=0; //index from of arr
$number=3; //number cell per row
echo "<table border='1'>";
while($row=array_slice($arr,$from,$number)){
echo "<tr>";
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>";
$from+=$number;
}
echo "</table>";
<?php
$arr = ['1','2','3','4','5','6','7','8','9'];
print "<table>\n";
foreach(array_chunk($arr, 3) as $row) {
print "<tr>";
foreach($row as $col) {
print "<td>";
print $col;
print "</td>";
}
print "</tr>\n";
}
print "</table>";
?>

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

Echo all row's into table

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

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