I was trying to fetch some data from mysql using PDO. For example, there is one table for brand names like Mercedes, Audi, Bently, Toyota. And there is another table for car names of each brand. The id s from the 'brand' tables are the foreign keys in the 'cars' table. Now I want to fetch all car names inside each brand name. Here is my code :
// Outer loop for Brands
$query = "SELECT * FROM brand";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$brand_name = $row->brand_name;
$brand_id = $row->id;
echo $brand_name;
echo "<br>";
// Inner loop for Cars
$query = "SELECT * FROM cars WHERE brand_id = $brand_id";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$car_name = $row->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
} // Ending of outer loop
But I got a problem here. The first brand name is fetched and then the inner loop runs and fetched the car names inside that brand. When the inner loop finished fetching all car names it should go to the outer loop again and find the next brand name. But it is not fetching the rest of the brand names and the car names as well. For example, if it finishes fetching all car names inside Toyota it doesn't go for the next brand name which is Audi.
But if I remove the inner while loop it fetched all the brand names without any errors. Please help me out with your best possible solutions. Thanks in advance.
$result&$rowvariables and that's why it is not working as the var values are overwritten