I have a table that contains over 16,000 records from a certain type of business. I am querying that table to get every city on file but I'm only displaying the city once with the number of instances in which the business exists in that city. "City #5" (City has five of these businesses) but I am getting repeats of certain cities as if their names are different and they are coming back out of order yet upon review they are not different.
I've checked for spaces or lack of spaces and cannot figure out why the query is thinking some businesses are not the same name when in fact they are. Is there a way to be more specific in my comparison?
Example of output:
Ft Collins #1 Ft Morgan #1 Ft Collins #87 Ft Garland #1 Ft Morgan #13
(notice Ft Collins and Ft Morgan: this was copy and pasted)
This is the code:
$rscc = sQ("SELECT corsCity FROM corsf
ORDER BY corsCity ASC");
if(!$rscc) {
echo "Houston... we have a problem!";
}
else {
$rows = 0;
$totalcities = 0;
$totalrows = 0;
$lastcity = 'xxxx';
while($ccrow = mysqli_fetch_assoc($rscc)) {
$currentcity = $ccrow['corsCity'];
if ($lastcity != $currentcity) {
if ($lastcity != 'xxxx') {
$rows++;
$totalcities++;
echo "$lastcity #$rows <br>";
$rows = 0;
}
$lastcity = $currentcity;
$totalrows++;
}
else {
$rows++;
$totalrows++;
}
}
echo "Total cities = $totalcities <br>";
echo "Total businesses = $totalrows <br>";
}
$rscc->close();
Btw, "sQ" just represents "$connection->query
".
Most of this can be done in SQL and you only have a simple loop to do in PHP.
Use GROUP BY
and Count()
to have the numbers per cities. Use WITH ROLLUP
to calculate the totals (and subtotals if you have several columns in the GROUP BY which is not your case)
SELECT corsCity AS City, COUNT(*) AS Nbr
FROM corsf
GROUP BY corsCity WITH ROLLUP
ORDER BY corsCity
Your query will return :
City | Nbr
-------------------
Chicago | 8
Houston | 10
Los Angeles | 2
New York | 5
NULL | 25
If the City is NULL
, its the total of all businesses