doujiyan0971 2014-03-26 10:55
浏览 29

使用php PDO和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.

  • 写回答

1条回答 默认 最新

  • dqnf28092 2014-03-26 10:59
    关注

    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 ;
    
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法