I have these two tables:
sections - {id,title,description}
topics - {id,section_id,topictitle}
Each section has multiple topics in the topics table.
after reading and trying I found using left join is the right way
$sql = 'select * from sections left join topics on sections.id=topics.sections_id';
$query = mysql_query($sql);
$section = array();
$i=0;
while ($sections = mysql_fetch_assoc($query)) {
$sl = array(
'title' => $sections['title'],
'topics'=> $sections['topictitle'],
);
$section[$i++] = $sl;
}
Is this the right code to view all sections and topics??
You’re selecting from
sectionsand joiningtopicsso you will only ever get one topic linked to each section, it won’t work if you have multiple topics linked to one section (which I think you have).Do it the other way around – select from
topicsand joinsections:Keep in mind that if you have a section that has no topics linked, you won’t get that section in your result set. If you want that then it’s worth selecting the sections first.
Also, instead of incrementing like that, you can just push to the array – you don’t need to manually manage the index: