I've been stuck on something for a couple of days now and I'm really hoping someone can help me please.
I have an array called $default_districts which generated by a query to find the postcode districts within a predefined radius from a point... so the number of values stored is dynamic.
[0] => NR1
[1] => NR12
[2] => NR13
[3] => NR14
... etc.
Ultimately, I'm trying to find out how many customers are within a "radius" from another address. So, I want to use those values binded to a prepared statement...
e.g.
// get data records within the default radius
if ($stmt = $mysqli->prepare("SELECT clientdata_urn, clientdata_district
FROM tblhub_clientdata
WHERE clientdata_district = ?)) {
// bind param to vars
$stmt->bind_param( // LOOP THROUGH $default_districts HERE // ));
// execute statement
$stmt->execute();
// store
$stmt->store_result();
// get numrows
$total_numrows = $stmt->num_rows;
// close statement
$stmt->close();
} else {
// error
printf("Error counting total data within default radius: %s
", $mysqli->error);
}
If I hardcode what I'm trying to create it would be something like this...
SELECT clientdata_urn, clientdata_district
FROM tblhub_clientdata
WHERE clientdata_district = 'NR1' OR clientdata_district = 'NR12' OR clientdata_district = 'NR13' OR clientdata_district = 'NR14'
I'm a bit of a newbie and any help would be greatly appreciated.
Thank you.
Welcome to SO, @Rachi. I believe this will solve your problem.
First, you're a lot better off using IN rather than a series of OR statements. I put together an SQLFIDDLE to demonstrate this.
This takes the form
SELECT COUNT(id) as num_users, clientdata_district
FROM tblhub_clientdata
WHERE clientdata_district IN ('NR12', 'NR14')
GROUP BY clientdata_district
The output gives you the number of users within each of the area codes in the array. If you want the total number of users in ALL areas within your area (your question wasn't clear) then simply remove the GROUP BY line like this.
The next challenge is to build your string so that you can put it into the query. The easiest way to do this is with the implode function.
$query_string = implode(",", $default_districts)
$sql = "SELECT COUNT(id) as num_users, clientdata_district";
$sql.= "FROM tblhub_clientdata";
$sql.= "WHERE clientdata_district IN ($query_string)";
$sql.= "GROUP BY clientdata_district";
NOTE that this will not add ' marks to your area codes, but from what I've seen of your codes I don't think that will matter. Worst case just throw away the implode statement and build the string in a FOR loop.