ivory- santos ivory- santos - 21 days ago 5
PHP Question

php-sql groups data with the same category

How can I print my fetch rows into groups of data?
For example i have these on my database

title category
one number
two number
three number
a letter
b letter
c letter


and I wanted to print it out on a different table.

table1 table2
number letter
one a
two b
three c


here's what I've tried.

$select = "SELECT * FROM `table` ORDER BY `category`";
$result = mysql_query($select);

$current_cat = null;

while ($rows = mysql_fetch_array($result))
{
if ($rows["category"] != $current_cat)
{
$current_cat = $rows["category"];
echo "<p>$current_cat</p>";
}
echo"$rows[title]";
}


the output of these codes is like this

number
one
two
three

letter
a
b
c


but then again, I wanted it to be in separate table.

Answer

You could add an if statement to test if the $current_cat is equal to the previous loops $current_cat. Do so by adding a new variable $last_cat, setting it equal to the current iterations $current_cat at the end of the while loop. Here is an example

   $select = "SELECT * FROM `table` ORDER BY `category`";
    $result = mysql_query($select);

    $current_cat = null;
    $last_cat = null;

    while ($rows = mysql_fetch_array($result)) { 

            if ($current_cat == null) {
        // Create a table with an id name of the first table
        echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
        }

    // Set the $current_cat to current loop category value
         $current_cat = $rows["category"];

    if ($last_cat != null) {
            if ($current_cat != $last_cat) {
            // Close table from previous $current_cat
        echo "</table>";
        // Create new table with id name of the category
        echo "<table id='" . $rows["category"] . "'>";
// Write the first row of the table - Category Title
echo "<tr class='categoryTitle'><td>" . $rows["category"] . "</td></tr>";
        }
    }

                            }
// Write new row in table with the value of the title
                echo "<tr><td>" . $rows[title] . "</td></tr>";

    // set the $last_cat to the value of $current_cat at the end of the loop
    $last_cat = $current_cat;
    } 

    // Close the last table after while loop ends
    echo "</table>";

This will allow you to create separate tables based on the category name no matter how many categories you have and allow you to style the tables based on the category name.