Jump to content

From DB Rows, to HTML Columns...


Xajel

Recommended Posts

I have a database with some records, as usual, each record use one row, the record has a lot of values in columns ( more than 50 columns )

 

the problem is when viewing the records as rows in HTML page the view is hard and take too much horizontal sliding.

 

so I want each record to be added as a new column rather than a new row. but the normal type of getting data from MySQL will let me get data row by row, not column by column. so is there's any way I can make this ? listing rows from db as columns ?

 

to make it more clear, I want to read the first column for each row, the using the normal while () {} loop I move to the next column and read it again row by row...

Link to comment
https://forums.phpfreaks.com/topic/94545-from-db-rows-to-html-columns/
Share on other sites


// load all records into an array of arrays
$the_array = array();
while ($row = mysql_fetch_array($result)) {
$the_array[] = array($row['col1'], $row['col2'], $row['col3']);
}

// now echo columns
for ($i=0;$i<3;$i++) { // here, 3 is the number of columns
foreach ($the_array AS $an_array) {
	echo $an_array[$i]."<BR>";
}
}

I am surprsied taht there isn't an html way to convert a table from cols and rows to rows and cols so to speak.  The way posted is  the real only way to do it however I'd change the while loop to

<?php
$data = array();
while($row = mysql_fetch_assoc($result)){
foreach($row as $key=> $value){
   $data[$key][] = $value;
}
?>

To save you some trouble.

 

 

If you have a lot of records you may want to to put them in blocks. This will also label the rows with the field name.

<?php
include 'db.php';
$data = $fields = array();

$rs = mysql_query ("SELECT * FROM tablename");

$kf = mysql_num_fields($rs);
for ($f=0; $f<$kf; $f++) $fields[] = mysql_fetch_field($rs, $f);

while ($row = mysql_fetch_row($rs)) $data[] = $row;

$kr = count($data);     // how many records? 

$numcols = 8;

for ($r=0; $r<$kr; $r+=$numcols)
{
    $block = array_slice($data, $r, $numcols);
    echo '<br><table border="1">';
    for ($i=0; $i<$kf; $i++)
    {
        echo '<tr>';
        echo '<th>', $fields[$i]->name, '</th>';
        foreach ($block as $rec)
        {
            echo '<td>', $rec[$i], '</td>';
        }
        echo '</tr>';
    }
    echo '</table><br>';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.