There are various problems with the code, your SQL doesn't need a HAVING clause, your trying to bind to a variable which isn't in the SQL statement...
function countTopics($mid,$forum){
$topics = implode(', ', array_column($mid, 'main_id'));
$query = "SELECT main_id, COUNT(*) as countID
FROM subtopics
WHERE main_id IN ($topics)
GROUP BY main_id";
if ( $stmt = $forum->prepare($query) ) {
if ( $stmt->execute() ) {
$rows = $stmt->fetchAll();
$count = implode(', ', array_column($rows, 'countID'));
$_SESSION['topics_count'] = $count;
}
}
}
Also you should check if the previous stage has worked - so 'if the statement prepare has worked' etc. Not sure what you would do if any of these fail, but that is down to your application design.
Not surewhat $forum
is as it doesn't seem to be used and it would be more normal to return the value of the count and let the calling code decide what to do with the value.
You probably want to do something like...
$rows = $stmt->fetchAll();
$_SESSION['topics_count'] = $rows;
and then later...
foreach ( $_SESSION['topics_count'] as $topic ) {
echo $topic['main_id'].'-'.$topic['countID'].PHP_EOL;
}
Update:
function countTopics($mid,$forum){
$topics = implode(', ', array_column($mid, 'main_id'));
$query = "SELECT main_id, subtopic_id, COUNT(*) as countID
FROM subtopics
WHERE main_id IN ($topics)
GROUP BY main_id, subtopic_id";
if ( $stmt = $forum->prepare($query) ) {
if ( $stmt->execute() ) {
$rows = $stmt->fetchAll();
$_SESSION['topics_count'] = $rows;
}
}
}
I've added a column called 'subtopic_id', this may need to be changed depending on your database column name. This will give rows as something like...
main_id subtopic_id countID
1 1 12
1 2 6
1 3 10
2 6 1
2 11 3
This means you will have multiple rows for each main_id, but they will have each sub topic and a count for that subtopic. If you want to output the data - you will have to use a loop, like the foreach
above.