loop to populate html table vertically [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I have a mysql query that returns an array of rows. How would i populate my html table using php vertically? there is no limit to how many columns i my HTML table allowed.
My MYSQL query returns about 40 columns per row.
MYSQL row1 => 10|11|12|13|14|15|16|17|18|19
row2 => 20|21|22|23|24|25|26|27|28|29
row3 => 30|31|32|33|34|35|36|37|38|39
HTML output should look like this
10 | 20 | 30
11 | 21 | 31
12 | 22 | 32
13 | 23 | 33
14 | 24 | 34
15 | 25 | 35
16 | 26 | 36
17 | 27 | 37
18 | 28 | 38
19 | 29 | 39
this is my code, and it's displaying nothing.
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
$c = 1;
while ($c <= $numrows)
{
$values['col_'.$c] = array();
$c++;
}
$r = 1;
while ($row = $_db->fetch_array($result))
{
$values['col_'.$c][$r] = $row;
$r++;
}
echo "<table border='1'>";
for ($r = 1; $r <= $numrows; $r++)
{
echo "<tr>";
for ($c = 1; $c <= sizeof($values['col_1']); $c++)
{
echo "<td>".$values['col_'.$c][$r]."</td>";
}
echo "</tr>" ;
}
echo "</table>" ;
Any idea what i'm doing wrong? or how to make it simpler? (i think there are too many while loops)

I think what you want is creating the php array from the mysql query, transposing the array (like you would transpose a matrix) and display it.
Transposing an array is a solved problem (transposing multidimentional arrays in php)
For the rest, it is pretty simple ... here is my code:
$res = mysqli_query(...);
$anarr = array();
while ($row = mysqli_fetch_array($res,$result_type=MYSQLI_ASSOC)){
$anarr[] = $row;
}
// here is the transpose part
array_unshift($anarr, null);
$transposedarr = call_user_func_array('array_map', $anarr);
// end of the transpose part
echo '<table>';
foreach ($transposedarr as $r){
echo '<tr>';
foreach ($r as $c){
echo '<td>'.$c.'</td>';
}
echo '</tr>';
}
echo '</table>';
?>

You are assigning only one row in your while loop. Change that with below code:
while ($row = $_db->fetch_assoc($result))
{
$values['col_'.$c][$r] = $row;
$c++;
$r++;
}
Here you are assigning the value to $value['col_1'][$r] and not increasing the value of $c. So at the end it override the values.

You can simplify the problem by just saying
$values[$rowIndex] = $columnArray
So in this case
$values[0] = array( 10, 20, 30 );
$values[1] = array( 11, 21, 31 );
And then loop across each array
echo "<table border='1'>";
foreach( $values as $row )
{
echo "<tr>";
foreach( $row as $columnValue )
{
echo ..whatever..
}
echo "<tr>";
}
echo "</table>" ;
Or something along these lines. I just basically psuedo coded this though, I have no access to php interpreter right now.

//while and foreach loop can do this
<?php
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
//check here
if($numrows>0)
{
//1 row
$r = 1;
//column
$c=0;
while ($row = $_db->fetch_assoc($result))
{
//value row column
$values[$r][$c] = $row;
//column == 3
if($c==2)
{
//increase row
$r++;
//reset column
$c = 0;
}else{
$c++;
}
}
echo "<table border='1'>";
//display row and columns
foreach($values as $row)
{
echo "<tr>";
echo "<td>".$values[0]."</td>";
echo "<td>".$values[1]."</td>";
echo "<td>".$values[2]."</td>";
echo "</tr>" ;
}
echo "</table>" ;
}

You can do everything in a single loop. Additionally, at least for your purposes in this example, I don't understand why you're putting everything in an array and then echo, instead of echoing it directly.
e.g. (tested):
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
echo "<table border='1'>";
$tab = array();
while ($row = $result->fetch_row())
{
$tab[] = $row;
}
for( $i = 0, $l = count($tab[$i]); $i < $l; $i++){
echo "<tr>";
for( $j = 0, $m = count($tab); $j < $m; $j++){
echo "<td>".$tab[$j][$i]."</td>";
}
echo "</tr>" ;
}
echo "</table>";
UPDATE: I completely changed my code. I didn't get initially what you needed.
Does this code help you?

This is how I would tackle it. The most difficult part is preparing the structure in which you prepare the table. It uses the following syntax: $somearray[] = $x, which appends $x to array $somearray. implode() concats an array together with a string you define. Last but not least, you were using mysql_fetch_assoc, which returns an associative array (Array( [column1] => "val1" ); etc). You want a numbered array instead for these kind of operations. This can be accomplished with mysql_fetch_array with a second argument of MYSQL_NUM.
$arrayOfRows = Array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$firstrun = true;
while( $row = $_db->fetch_array($result, MYSQL_NUM) ) {
#Setup structure on first run
if( $firstrun ) {
$firstrun = false;
for( $i = 0; $i < count( $row ); $i++ ) {
$arrayOfRows[$i] = Array();
}
}
#Each field in this mysql row needs to be in a different html row
foreach( $row as $k => $v ) {
$arrayOfRows[$k][] = $v;
}
}
#Now simply print it
echo '<table>';
foreach( $arrayOfRows as $k => $row ) {
echo '<tr>';
echo '<td>' . implode( '</td><td>', $row ) . '</td>';
echo '</tr>';
}
echo '</table>';

<?php
$arr = array(array(1,2,3,4,5,6,7,8,9), array(10,11 etc . . .
for($i = 0; $i < 9; ++ $i){
for($x = 0; $x < $num_rows; ++ $x){
echo $arr[$x][$i];
}
echo '<br/>';
}
?>
U may replace 9 with number of columns in tables
I not shure what it this code correct (can't test now), but i think it can help you
Sorry if i do something wrong, i just try to help

Related

php display array data in multiple columns by using ceil function

For example, I have a array with 8 data. I want to display in this format
$a = array(1,2,3,4,5,6,7,8);
======
1 2
3 4
5 6
7 8
=====
OR array with 11 data
$a = array(1,2,3,4,5,6,7,8,9,10,11);
=========
1 2 3
4 5 6
7 8 9
10 11
=========
Not sure which part i got wrong. Here is my code
$a = array(1,2,3,4,5,6,7,8);
$c = ceil(count($a)/2);
echo "<table>";
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i].'</td>';
echo '<td>'.$a[$i+1].'</td>';
}
echo "</table>";
However, my data display in this way instead
======
1 2
2 3
3 4
4 5
=====
Basically, I want to display my data from mysql in this format. But before that, I need to test out the ceil function and see if its working. Anyone knows whats wrong with my coding?
Since you have 2 cels per row you need to calculate the actual index. Also don't forget to close the <tr>
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i * 2].'</td>';
echo '<td>'.$a[$i * 2 + 1].'</td>';
echo '</tr>';
}
Here is a full example of a cleaner solution:
<?php
$a = array(1,2,3,4,5,6,7,8);
$cols = 2;
$c = ceil(count($a) / $cols);
echo "<table>";
for($i = 0; $i < $c; $i++){
echo "<tr>";
for ($col = 0; $col < $cols; $col++) {
$value = isset($a[$i * $cols + $col]) ? $a[$i * $cols + $col] : '';
echo '<td>'. $value .'</td>';
}
echo "</tr>";
}
echo "</table>";
If you increase it manually you have to skip 1 loop every time.
$a = array(1,2,3,4,5,6,7,8,9,10,11);
$size = sizeof($a);
/* Your magic method to determine the total table cols.
*/
$cols = 3;
#$cols = 2;
echo "<table>";
for($i = 0; $i < $size; $i+=$cols){
echo "<tr>";
for($c = 0; $c < $cols; $c++){
if($i+$c >= $size){
break;
}
echo '<td>'.$a[$i+$c].'</td>';
}
echo "</tr>";
}
echo "</table>";
I've used the method of math to determine if it should print or not because it is faster. However, if you have empty indexes in the array you might want to use the isset() method as the whole code in the inner for loop.
if(isset($a[$i+$c])){
echo '<td>'.$a[$i+$c].'</td>';
}

how to fetch all rows data from the database using while loop and stored fetch values in variables in php

hi everyone i have table in the database from where i fetch data one column of table has user input n i fetch the data on the basis of user input like if user enter 2 in the textbox only that rows that contain number 2 will display
like
code of insertion on the basis of no of room
<?php
$d=$_POST['roomno'];
echo $d;
?>
<?php
//database connection
$db = new PDO("mysql:host=localhost;dbname=ems",'root','');
//query
$sql = "INSERT INTO table1 (c,c1, c2, c3, c4,c5,c6,c7,c8,c9,c10,c11,c12,c13) VALUES ('',:c1, :c2, :c3, :c4,:c5, :c6, :c7, :c8, :c9,:c10, :c11, :c12,'$d')";
$stmt = $db->prepare($sql);
foreach ($data_t1 as $i => $value) {
$stmt->execute(array(
':c1'=>$data_t1[$i],
':c2'=>$data_t2[$i],
':c3'=>$data_t3[$i],
':c4'=>$data_t4[$i],
':c5'=>$data_t11[$i],
':c6'=>$data_t22[$i],
':c7'=>$data_t33[$i],
':c8'=>$data_t44[$i],
':c9'=>$data_t111[$i],
':c10'=>$data_t222[$i],
':c11'=>$data_t333[$i],
':c12'=>$data_t444[$i],
));
} ?>
coding for fetchng the data
<?php
include('config.php');
$sa="select * from table1 where c13='$d'";
$result=mysql_query($sa) or die(mysql_error());
echo "<table border='1'>
<tr>
</tr>";
<?php
$i = 1;
while($row = mysql_fetch_array($result)) {
echo ${"r" . $i . "1"} = $row['c'];
echo ${"r" . $i . "2"} = $row['c1'] ;
echo ${"r" . $i . "3"} = $row['c2'];
echo ${"r" . $i . "4"} = $row['c3'];
echo ${"r" . $i . "5"} = $row['c4'];
$i++;
}
result
$d=3;mean user enter 3
3 room deatils enter in three rows of table like ths
row1 2 4 5 6 3(user enter value)
row2 12 14 15 16 3(user enter value)
row3 22 44 55 63 3(user enter value)
now as i mention in my fetch query that fetch the data where c13(room)=user input($d);
result of theses above three row display
now i want to store each of theses three row values in different varaibles
in the similar manner if user enter 2 or 4 i want to store two or four rows values in different varaible
Of course it will display only the last row. Within each iteration over the query result you are rewriting the $r -nth variable, so the result you'll see after the loop are only the values that were assigned during the last iteration.
Use
$row = array();
while($row[] = mysql_fetch_array($result)){
}
As result you will get all the data stored as an array in $row.
What it does is as follows:
Iterates over the query result and and fetching it. The fetching method returns an array of the current iterated row values. This array is pushed into the $row array. So, each row value could be accessed at a corresponding index of $row.
Use print_r( $row ); to see the structure.
Further use of the array is as follows:
echo $row[ 0 ][ 'c1' ];
echo $row[ 0 ][ 'c2' ];
echo $row[ 1 ][ 'c3' ];
If you want to show the input depending on a dynamical rows amount, use this:
$count = count( $row );
for( $i = 0 ; $i < $count; $i++ ){
echo $row[ $i ][ 'c1' ];
}
Simply:
$data = array() ; //Declare an array
while($row = mysql_fetch_array($result)){
$data[] = $row ; //Add every row to array
}
echo $data['c4'] ; // Work with the array ETC
I recommand you to use Michael Sazonov's way.. but if you don't want arrays here you go:
<?php
$i = 1;
while($row = mysql_fetch_array($result)) {
${"r" . $i . "1"} = $row['c'];
${"r" . $i . "2"} = $row['c1'] ;
${"r" . $i . "3"} = $row['c2'];
${"r" . $i . "4"} = $row['c3'];
${"r" . $i . "5"} = $row['c4'];
$i++;
}
Now The contents are stored in $r11 $r12 $r13.. $r35 and you have to echo them manually or using 2 for loops
<?php
for($i=1; $i<=3; $i++) {
for($j=0; $j<=5; $j++) {
echo ${'r'.$i.$j};
}
}
?>

create id column using php loop

I want an id column generated by php loop and I tried the code below.
This code is working but it skips first row. For e.g. if there are 153 rows, it shows only 152 rows because it skips first row and starts numbering from second row.
$i = 0;
$result = mssql_query ($sql);
$cell = mssql_fetch_array($result);
while ($i <= $cell & $cell = mssql_fetch_array($result))
{
$i = $i + 1;
echo "<tr><td>".$i."</td>";
echo "<td>".$cell[0]."</td>";
echo "<td>".$cell[1]."</td>";
echo "<td>".$cell[2]."</td>";
echo "<td>".$cell[3]."</td>";
echo "<td>".$cell[4]."</td>";
echo "<td>".$cell[5]."</td>";
echo "</tr>";
}
$cell = mssql_fetch_array($result);
^^^^^^^^^^^^^^^^^
fetches the first record
while ($i <= $cell & $cell = mssql_fetch_array($result))
^^^^^^^^^^^^^^^^^
fetches the second record
You're never outputting the first record you're fetching.
No idea what you're trying to do with that $i condition.
$i = 0;
$result = mssql_query ($sql);
//$record = mssql_fetch_array($result); - you don't need this
while ($cell = mssql_fetch_array($result)) //you dont need $i <= $cell
{
$i++; //$i = $i + 1;
echo "<tr><td>".$i."</td>";
echo "<td>".$cell[0]."</td>";
echo "<td>".$cell[1]."</td>";
echo "<td>".$cell[2]."</td>";
echo "<td>".$cell[3]."</td>";
echo "<td>".$cell[4]."</td>";
echo "<td>".$cell[5]."</td>";
echo "</tr>";
}
I'm guessing you probably want && instead of & here:
while ($i <= $cell & $cell = mssql_fetch_array($result))

Spliting PHP/MySQL data into 3 columns

I need to create 3 HTML columns in PHP with data returned from MySQL. I would like the data split evenly between all 3 columns... How would I go about doing this?
You could try doing something like this:
$result = mysql_query("SELECT value FROM table");
$i = 0;
echo '<table><tr>';
while ($row = mysql_fetch_row($result)){
echo '<td>' . $row[0] . '</td>';
if ($i++ == 2) echo '</tr><tr>'
}
echo '</tr></table>';
note this table has the values ordered like
1 2 3
4 5 6
7 8 9
If you wanted it vertically like
1 4 7
2 5 8
3 6 9
Then you should do something like
$result = mysql_query("SELECT value FROM table");
$data = Array();
while ($row = mysql_fetch_row($result)) $data[] = $row;
for ($i = 0; $i < count($data) / 3; $i++){
echo '<table><tr>';
for ($j = 0; $j < 3; $j++){
echo '<td>' . $data[ $i + $j * 3] . '</td>';
}
echo '</tr><tr>'
}
echo '</tr></table>';
You can create an HTML table and then use a PHP foreach loop to loop through the MySQL result set and put each field in its own table. At the end of each record returned by the MySQL query, end the table row and start a new one.
A small detail, if return more entries than the "fetch_row" use "break", based on the answer from #Robbie: Spliting mysql data in 3 columns error -3-columns-error

PHP loop to sort table

I'm querying a database for names that are numbered 1-26 alphabetically. I have the following code, but since HTML is structured tr then td, the table appears alphabetically by row as opposed to by column. How can I make it appear in order by column?
$query = mysql_query("SELECT name FROM people WHERE main=1 ORDER BY id");
$i = 0;
while($result = mysql_fetch_array($query)) {
$name = $result['name'];
if ($i % 5 == 0) echo "<tr>\n";
echo "<td width=\"150\">";
echo "".$name."<br />";
echo "</td>\n";
$i++;
if ($i % 5 == 0) echo "</tr>\n";
};
alpha beta charlie
delta echo foxtrot
vs.
alpha charlie echo
beta delta foxtrot
Also, I'm open to reworking the code if there's a more efficient way.
You could just access the output array in strides. Compute how many rows you need as the number of results divided by 5, and use the row count as the stride.
$ncols = 5;
$nrows = $nresults / $ncols + ($nresults % $ncols == 0 ? 0 : 1);
for ($i = 0; $i < $nrows; $i++)
{
// start row
for ($j = 0; $k < $ncols; $j++)
{
// print $results[$nrows * $j + $i]
}
// end row
}
You'll have to transfer your query results into an array $results first. Since you'll have to know the total number of results, this is sort of mandatory, though I'd be curious if anyone has a solution that can work while fetching the results.
Update: See Justin's answer for a cool solution that grows the output while fetching the query results line by line. Since it's currently being worked on, here's a summary (credits to Justin):
$nresults = mysql_num_rows($query);
$ncols = 5;
$nrows = (int) ceil($nresults / $ncols);
$i = 0; $cols = array_fill(0, $nrows, "");
while ($result = mysql_fetch_array($query))
$cols[$i++ % $nrows] .= "<td>$result['name']</td>";
echo "<tr>" . implode("</tr><tr>", $cols) . "</tr>";
Edit:
After the discussion in the comments between myself, Kerrek SB and the OP bswinnerton, the following code seems to be the most effective:
$columns = 3;
$rowcount = mysql_num_rows($query);
$rows = ceil($rowcount / $columns);
$rowdata = array_fill(0, $rows, "");
$ctr = 0;
while ($result = mysql_fetch_array($query))
$rowdata[$ctr++ % $rows] .= '<td>'.$result['name'].'</td>';
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
This will create three columns, filled vertically (my original answer would create three rows). It also properly initializes the array (preventing PHP warnings), yields a correct row count for result counts that aren't divisible by the column count, and incorporates Kerrek's clever "calc-row-in-the-subscript" trick.
Original Post:
You could use arrays and implode() This way, you only have to make one pass through your results:
$row = 0;
$rows = 3;
$rowdata = array();
while($result = mysql_fetch_array($query))
{
if ($row >= $rows) $row = 0;
$rowdata[$row++] .= '<td>'.$result['name'].'</td>';
}
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';

Categories