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?
4
-
1This is nothing to do with PHP/MySQL. This is an HTML question...Oliver Charlesworth– Oliver Charlesworth2011-12-28 19:43:50 +00:00Commented Dec 28, 2011 at 19:43
-
@Chris: Yes, but presumably the problem is what HTML to generate.Oliver Charlesworth– Oliver Charlesworth2011-12-28 19:46:57 +00:00Commented Dec 28, 2011 at 19:46
-
@Michael, How should it be broken up? Should items be ordered horizontally, then vertically (first row is 1 2 3, second is 4 5 6), or vertically first (first row is 1 3 5, second is 2 4 6)?Chris Marasti-Georg– Chris Marasti-Georg2011-12-28 19:47:47 +00:00Commented Dec 28, 2011 at 19:47
-
Using the mans code below I'd like to have it broken up horizontally. How would I go about doing this?Michael Grigsby– Michael Grigsby2011-12-28 20:13:06 +00:00Commented Dec 28, 2011 at 20:13
Add a comment
|
3 Answers
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>';
4 Comments
tereško
FFS, please stop using the ancient
mysql_* functions and teaching others to do it. -1arcyqwerty
I would normally use PDO but how the data is retrieved isn't the focus of my response. The question asked how to get data into 3 columns and the approach used can be used regardless of how the resultant rows are obtained
arcyqwerty
No problem! :) Glad to be of service
Michael Grigsby
@tereško, he's cool. I usually use the mysqli functions that come packaged with Ci (CodeIgniter)... So whenever I get code like this, I just port it over.
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