i want to do the following but haven't found how to.
Or i'm not sure if there is a better way / practice, if you can point me that way i will appreciate it.
I have 2 tables on my DB
- Table1 : Categories
- Table2 : Subcategories
Table2 is associated with table1 by the primary key.
So for 1 row in the table1 i can have multiple associated rows on the table2.
I query and fetch the data on my Table1 like this:
$result = $mysqli->query("SELECT * FROM table1");
$post = array();
while ($row = $result->fetch_object()){
$row->sub = get_subcategories($row['id']); /* this value is added to the array since i want to store in here the associated arrays from the table2 */
$post[] = $row;
}
return $post;
Then i do the following query also on another function for the table2 data based on every id from the table1
function get_subcategories($id){
$result = $mysqli->query("SELECT * FROM table2 where categories_id = '$id'");
$post = array();
while ($row = $result->fetch_object()){
$post[] = $row;
}
return $post;
}
But the result im getting when using var_dump doesn't seem right.
Can i do it? or what am i doing wrong?
Thanks in advance
$post, but returning$posts(with an extras).$row['sub']won't work when you usefetch_object, it should be$row->sub.