Xajel Posted March 5, 2008 Share Posted March 5, 2008 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... Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted March 5, 2008 Share Posted March 5, 2008 // 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>"; } } Quote Link to comment Share on other sites More sharing options...
cooldude832 Posted March 5, 2008 Share Posted March 5, 2008 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. Quote Link to comment Share on other sites More sharing options...
Barand Posted March 5, 2008 Share Posted March 5, 2008 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>'; } ?> Quote Link to comment Share on other sites More sharing options...
Xajel Posted March 8, 2008 Author Share Posted March 8, 2008 Thanks all for the help, I choosed to use Barand way as this one is more sutable for me, every thing is working good now... thought I'll need to make some functions now for Cell formatting Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.