Steven Trainor
Steven Trainor

Reputation: 1255

Manipulating MySQL Results with HTML Table using PHP

I am hoping someone can help me. I am creating a hardware web page that - In the content section will display the main categories which are read from the database. I want the results to be read as 3 per row and 2 columns as there are 6 categories. Similar to what i have below.

| CAT1 | CAT2 | CAT3 |
| CAT4 | CAT5 | CAT6 |

I currently have it displaying in columns but it is just duplicating the same data in all the columns. i.e.

| CAT1 | CAT1 | CAT1 |
| CAT2 | CAT2 | CAT2 |

Let me know if anyone has any ideas.

Here is the code I am using:

$query = "SELECT distinct category FROM listings";
$result = mysql_query($query);

echo "<table>";

while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['category'] . "</td><td>" . $row['category'] . "</td></tr>";
}

echo "</table>";

Upvotes: 0

Views: 198

Answers (3)

Neeraj Kumar
Neeraj Kumar

Reputation: 1058

This work for all categories as long as you want.

$catNo = 1;

echo "<table> <tr>";

while($row = mysql_fetch_array($result)){
    echo "<td>" . $row['category'] . "</td>";
    if ($catNo % 3 == 0) {
       echo "</tr><tr>"
    }
    $catNo++;
}

echo "</tr> </table>";

Upvotes: 2

gmiley
gmiley

Reputation: 6604

The problem you are running into is that you are printing the same value in each column because $row is not being moved to the next iteration. Given your output from your query you could do the following:

echo "<table><tr>";
$idx = 0;
while($row = mysql_fetch_array($result)) {
   if(++$idx % 3 == 0) {
      echo "</tr><tr>";
   }
   echo "<td>" . $row['category'] . "</td>";
}
echo "</tr></table>";

The % operator is a modulo operator and returns the remainder of the operator divided by the operand. In this case $idx divided by 3, so after 3 rows "</tr><tr>" is echoed, then it is all closed after the loop is finished.

Upvotes: 2

Daniel Stanley
Daniel Stanley

Reputation: 1050

The issue is with your while statement using the same row for each <td>, you could use a counter to check when to put a new row:

$catNo = 1;

echo "<table> <tr>";

while($row = mysql_fetch_array($result)) {
    echo "<td>" . $row['category'] . "</td>";
    $catNo++;
    if ($catNo == 3) {
        echo "</tr><tr>"
        //if you end up having more than six categories reset $catNo
        $catNo = 1;
    }

}

echo "</tr> </table>";

Upvotes: 2

Related Questions