0

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.

Currently I am using the logic below, however I am getting everything in a column.

The goal is to limit the data to a page size so the data can be printed.

<div>
$result = mysql_query("SELECT * FROM master_data");

echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>"; 


mysql_close($con);
?></div>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MysticRose
  • 47
  • 5
  • Use [PDO or mysqli](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1). – Jonast92 Jan 26 '15 at 14:55
  • 1
    `if ($count++ >= 4) { start new row; $count = 0; }`, basically. – Marc B Jan 26 '15 at 14:57
  • Please show us what type of output you want and also what is your database structure. It will help! – A.D. Jan 26 '15 at 14:59
  • @MarcB Right side `++` gets evaluated *after* the comparison, so you'd end up with 5 iterations per row. Just sayin. – lafor Jan 26 '15 at 15:08
  • @A.D. Basically Every column contains basic information such as Name, Address etc. Just small blocks of information about each person. – MysticRose Jan 26 '15 at 15:39

2 Answers2

1

If I understand your problem correctly you will want to do something like:

Keep a counter to see which number record you're looking at ($i)

$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
    // ...

On every 4th iteration of the loop output something like </tr><tr>.

    if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
    {
        echo "</tr><tr>"; // Output your HTML to start a new row
    }

One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.

Jonathon
  • 15,873
  • 11
  • 73
  • 92
0
<div>
$result = mysql_query("SELECT * FROM master_data");

echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>"; 

mysql_close($con);
?>
</div>
Ian Thompson
  • 187
  • 1
  • 10