简体   繁体   中英

return row in row value using php PDO and MySQL

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.

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM