At the below I have 2 tables. in first table I have a list of Models. on Second table I have added keys for some models. For example, i have added 2 keys (123 AND 125) for model with Id
1
models
id(AI) model
1 100
2 101
3 100
4 105
5 107
modelKeys
keyid(AI) model_id key
1 1 123
2 1 125
3 4 125
4 5 127
Now, using PHP PDO I want to list all models and model's keys.
<?php
$query =
"
SELECT
m.*,
mk.*
FROM
models as m
LEFT JOIN modelKeys as mk
ON m.id = mk.model_id
ORDER BY
m.id
";
$sql = $db -> query($query);
$sql -> execute();
$fetch = $sql -> fetchAll(PDO::FETCH_ASSOC);
?>
<ol>
<?php
foreach($fetch as $models)
{
echo "
<li>
$models[model]";
foreach($fetch as $keys)
{
echo "<ul>";
if($models['id'] == $keys['keyid'])
{
echo "<li>$keys[key]</li>";
}
echo "</ul>";
}
</li>";
}
?>
</ol>
RESULT
model
100
123
125
100
123
125
101
100
105
125
107
127
As you see, model with number 100 is duplicated, cause it has 2 keys. I tried to use SELECT DISTINCT
and GROUP BY
but did not get correct result.
CORRECT RESULTS SHOULD BE
model
100
123
125
101
100
105
125
107
127