Skip to content
Advertisement

php echo each unique sql order by

From a db table I query all the results and order those by place. I echo this query into checkboxes. So every place has its own checkbox. Above all the checkboxes there is a title like select one or multiple places but now I would also like to add a title to each set of places.

I have the following column in a database:

id, ewladressenplaats, postalcode
1 amsterdam 1001
2 amsterdam 1002
3 amsterdam 1003
4 rotterdam 2001
5 rotterdam 2002
6 maastricht 3001
7 hengelo 4001
8 hengelo 4002

I run this sql query:

$query = 'SELECT * FROM ##_adressen_adres ORDER BY ewladressenplaats';

Then I echo this:

echo "<div";
  echo "<div class='header'>Selecteer een of meerdere plaatsen</div>";
  foreach($rows as $row) {
    echo "<div class=''> <label for='".$row->ewladressenplaats."'>".$row->ewladressenplaats."</label><input type='checkbox' name='".$row->ewladressenplaats."' value='".$row->ewladressenpostcodes."'></div>";
  };
echo "</div>";

This creates in total 8 checkboxes and looks a bit like this [] = checkbox

**Selecteer een of meerdere plaatsen**
amsterdam []
amsterdam []
amsterdam []
rotterdam []
rotterdam []
maastricht []
hengelo []
hengelo []

But how can I make it echo like this:

**Selecteer een of meerdere plaatsen**
**amsterdam**
amsterdam []
amsterdam []
amsterdam []
**rotterdam**
rotterdam []
rotterdam []
**maastricht**
maastricht []
**hengelo**
hengelo []
hengelo []

Advertisement

Answer

First group it for the first loop then get the plaats column of the group and create new query then add condition to it then create inner loop for group data, this code base on your data from your sqlfiddle

    echo "<pre>";

    $group_sql = "SELECT * FROM tbl GROUP BY plaats";
    $group = $conn->query($group_sql);

    while($row = $group->fetch_assoc()) {

        $inner_sql = "SELECT * FROM tbl WHERE plaats = '" . $row['plaats'] . "' ORDER by plaats";
        $inner = $conn->query($inner_sql);

        echo "Group : " . $row['plaats'] . PHP_EOL;

        while($inner_row = $inner->fetch_assoc()) {

            echo "Plaats : " . $row['plaats'] . " Postal Code : " . $inner_row['postal_code'] . PHP_EOL;

        }

        echo "<br>";


    }

    echo "</pre>";

Which Return like this

Group : Amsterdam
Plaats : Amsterdam Postal Code : 1001
Plaats : Amsterdam Postal Code : 1002
Plaats : Amsterdam Postal Code : 1003

Group : Hengelo
Plaats : Hengelo Postal Code : 4001
Plaats : Hengelo Postal Code : 4002

Group : Maastricht
Plaats : Maastricht Postal Code : 3001

Group : Rotterdam
Plaats : Rotterdam Postal Code : 2001
Plaats : Rotterdam Postal Code : 2002
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement