cars models
car_id car car_id model_id model
1 ford 1 1 mustang
2 fiat 1 2 focus
3 toyota 1 3 escort
2 4 500
2 5 spider
3 6 tacoma
The two tables I have are much more complicated so I took this code from another users question, It is almost what I want, but I don't know how to get the output to format with PHP correctly
SELECT c.Car, m.Model_id, m.Model
FROM models m
INNER JOIN car c ON c.Car_id = m.Car_id
WHERE m.Car_id = (SELECT Car_id FROM models WHERE Model = 'Escort');
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$model = $row['Model'];
$vehicle = $row['Car'];
ford mustang
ford focus
ford escort
What I am trying to get is
ford
mustang
focus
escort
I have posted my updated attempt below, which works, but I bet you fine people could make it prettier.
$sql = "
SELECT c.Car, m.Model_id, m.Model
FROM models m
INNER JOIN car c
ON c.Car_id = m.Car_id
WHERE m.Car_id = '1' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$vehicle[$row['Car']][] = $row['Model'];
}
echo "<table>";
foreach( $vehicle as $value => $key )
{echo '<tr><td>'.$value.'</td></tr>';
foreach( $key as $mod)
{echo '<tr><td>'.$mod.'</td></tr>';}}
}
Results in:
ford
mustang
focus
escort
<?php
$mo1 = "";
$sql = "SELECT c.Car, m.Model_id, m.Model FROM models m INNER JOIN car c ON c.Car_id = m.Car_id
WHERE m.Car_id = (SELECT Car_id FROM models WHERE Model = 'Escort')";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$model = $row['Model'];
$vehicle = $row['Car'];
if($mo1 != $mo){$data.="<tr>
<td>$model</td>
</tr>";
}
$data.="<tr>
<td>$vehicle</td>
</tr>";
$mo1=$mo;
}
?>
You probably want an array with the key as the car type. Loop you're results and append to an array as necessary.
Ex:
vehicle=[];
while($row = mysqli_fetch_assoc($result)) {
if (!array_key_exists($row['Car'], $vehicle)){
$vehicle[$row['Car']] = [];
}
$vehicle[$row['Car']][] = $row['Model'];
}
Output will look like this:
array(1) {
["Ford"]=>
array(2) {
[0]=>
string(4) "focus",
[1]=>
string(6) "escort"
}
}