Reputation: 29
This is my code
public function count_er($str_arr){
for($i=0;$i<=count($str_arr);$i++){
$counter=("SELECT COUNT(*) FROM `number` where `group_id`='$str_arr[$i]'");
$q = mysqli_query($this->con,$counter);
$row .= $q->fetch_row();
}
return $row[0];
mysqli_close($this>con);
}
}
Upvotes: 1
Views: 40
Reputation: 26450
You're better off using a single query, and using a prepared statement. Then loop over all the results and store them in an array, which you return.
public function count_er(array $str_arr) {
$result = [];
$query = "SELECT group_id, COUNT(*)
FROM `number`
WHERE `group_id` IN (".trim(str_repeat("?,", count($str_arr)), ',').")
GROUP BY `group_id`";
$stmt = $this->con->prepare($query);
// "i" for integers, "s" for strings
$stmt->bind_param(str_repeat("i", count($str_arr)), ...$str_arr);
$stmt->execute();
$stmt->bind_param($group_id, $count);
while ($stmt->fetch()) {
$result[$group_id] = $count;
}
$stmt->close();
return $result;
}
Upvotes: 1