0

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>";

3 Answers 3

2

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

Comments

2

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>";

Comments

2

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.

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.