table projects
+----+--------+------------+
| id | title | project_id |
+----+--------+------------+
| 1 | blue | 12345 |
| 2 | red | 67890 |
| 3 | yellow | 11111 |
| 4 | rosa | 22222 |
+----+--------+------------+
table connect
+----+------------+-----------+
| id | project_id | people_id |
+----+------------+-----------+
| 1 | 12345 | 4 |
| 2 | 12345 | 3 |
| 3 | 12345 | 2 |
| 4 | 22222 | 2 |
+----+------------+-----------+
table people
+----+-----------+-----------+----------+
| id | firstname | name | position |
+----+-----------+-----------+----------+
| 1 | Diana | Rose | singer |
| 2 | Al | Capone | singer |
| 3 | Barbara | Streisand | actor |
| 4 | Ben | Harper | musician |
+----+-----------+-----------+----------+
This is the result I wish:
+----+---------+--------+----------+----------+
| id | project | singer | musician | actor |
+----+---------+--------+----------+----------+
| 1 | blue | Capone | Harper | Sreisand |
| 4 | rosa | Capone | | |
+----+---------+--------+----------+----------+
I tried to achieve the result like this:
<?php
$pdo = $db->query('
SELECT *
FROM projects
LEFT JOIN connect ON projects.project_id=connect.project_id
LEFT JOIN people ON connect.people_id=people.id;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo <td>$row['title']</td>;
echo "<td>";
if ($row['position']== "singer"){echo $row['name'];}
echo "</td>";
echo "<td>";
if ($row['position']== "musician"){echo $row['name'];}
echo "</td>";
echo "<td>";
if ($row['position']== "actor"){echo $row['name'];}
echo "</td>";
}
?>
But my result is:
+----+---------+--------+----------+----------+
| id | project | singer | musician | actor |
+----+---------+--------+----------+----------+
| 1 | blue | Capone | | |
| 1 | blue | | Harper | |
| 1 | blue | | | Sreisand |
| 4 | rosa | Capone | | |
+----+---------+--------+----------+----------+