Reputation: 765
I am currently using two tables that look like:
tasks(user1, user2)
users(id, name)
I am performing the following query:
SELECT * FROM tasks
LEFT JOIN users u1 ON tasks.user1 = u1.id
LEFT JOIN users u2 ON tasks.user2 = u2.id
I am using PHP PDO to execute the query and returning an array which I then encode to json like so:
$query = $con->prepare($SQL);
$query -> execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json');
echo json_encode($result);
My problem is that the user2 values overwrite the user1 values in the $result array, is there a way I can return something like:
[{"user1": {"id": "value", "name":"value"}, "user2": {"id": "value", "name":"value"}}]
so that each user is a new set of data inside the users key value.
Any thoughts on how to do this? I am fairly new to PDO.
Upvotes: 0
Views: 57
Reputation: 1271151
You need to give them different aliases (column names) in the query:
SELECT t.*, u1.name as name1, u2.name as name2
FROM tasks LEFT JOIN
users u1 ON tasks.user1 = u1.id LEFT JOIN
users u2 ON tasks.user2 = u2.id ;
Upvotes: 1