3

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
  • 1
    This is nothing to do with PHP/MySQL. This is an HTML question... Commented Dec 28, 2011 at 19:43
  • @Chris: Yes, but presumably the problem is what HTML to generate. Commented 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)? Commented 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? Commented Dec 28, 2011 at 20:13

3 Answers 3

8

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>';
Sign up to request clarification or add additional context in comments.

4 Comments

FFS, please stop using the ancient mysql_* functions and teaching others to do it. -1
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
No problem! :) Glad to be of service
@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.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.