Printing a variable only when it changes?
- by user1781639
First off, my question was a little vague or confusing since I'm not really sure how to phrase my question to be specific. I'm trying to query a database of stockists for a Knitting company (school project using PHP) but I'm looking to print the city as a heading instead of with each stockists information.
Here is what I have at the moment:
$sql = "SELECT * FROM mc16korustockists where locale = 'south'";
$result = pg_exec($sql);
$nrows = pg_numrows($result);
print $nrows;
$items = pg_fetch_all($result);
print_r($items);
for ($i=0; $i<$nrows2; $i++) {
print "<h2>";
print $items[$i]['city'];
print "</h2>";
print $items[$i]['name'];
print $items[$i]['address'];
print $items[$i]['city'];
print $items[$i]['phone'];
print "<br />";
print "<br />";
}
I'm querying the database for all of the data in it, the rows being ref, name, address, city and phone, and executing it. Querying the number of rows then using that to determine how many iterations for the loop to run is all fine but what I'd like to have is for the h2 heading to appear above the for ($i=0;) line.
Trying just breaks my page so that might be out of the question. I figure I'd have to count the number of entries in 'city' until it detects a change then change the heading to that name I think? That or make a heap of queries and set a variable for each name but at point, I might as well do it manually (and I highly doubt it would be best practice). Oh, and I'd welcome any critiques to my PHP since I'm just starting out.
Thanks and if you need any more information, just ask!
P.S. Our class is learning with PostgreSQL instead of MySQL as you can see in the tags.