简体   繁体   English

查询多个MySQL表并将数据编码为JSON

[英]Querying more than one MySQL table and encoding the data as JSON

I'll admit, I don't know tons about MySQL queries or JSON for that matter but I would like to. 我承认,对此我不了解MySQL查询或JSON,但我想知道。 Currently when I get data from my database I query one table which brings values into another query and so on. 当前,当我从数据库中获取数据时,我查询一个表,该表将值带入另一个查询,依此类推。 I don't think this is the best practice to go about receiving all the data I need to display. 我认为这不是接收我需要显示的所有数据的最佳实践。 Below is an example of how my MySQL queries currently work in a PHP foreach function: 以下是我的MySQL查询当前在PHP foreach函数中如何工作的示例: 在此处输入图片说明

So, is there a better way of completing the query(s) I want and how would I be able to encode it as JSON? 因此,是否有更好的方法来完成我想要的查询,以及如何将其编码为JSON?

Any help would be appreciated, thank you. 任何帮助,将不胜感激,谢谢。

From what I understand, your code is doing something like this: 据我了解,您的代码正在执行以下操作:

<?php
$friends = query("SELECT Friends");
while($row = fetch_object($friends)){
    $friend_dets = query("SELECT Friend_dets WHERE Friend_ID = $row->Friend_ID");
    $output[] = fetch_assoc($friend_dets);
}
echo json_encode($output);
?>

With this, you're making the process more complex than it needs to be. 这样,您使过程变得比所需的复杂。 You can get all of the information you need with one query with a JOIN like this: 使用JOIN这样的一个查询就可以获取所需的所有信息:

SELECT Name, Status, WhateverElseYouWant
FROM Friends
    JOIN Profiles ON (Friends.friend-profile-id = Profiles.profile-id)
WHERE Friends.profile-id = MyCurrentProfileID

That will give you the name, status and whatever else of everyone who is friends with MyCurrentProfileID . 这将为您提供名称,状态以及与MyCurrentProfileID成为朋友的每个人的其他MyCurrentProfileID Then, you just need to put the result in an array and json_encode it: 然后,您只需要将结果放入数组中并对其进行json_encode

<?php
$friends = query($QueryFromAbove);
while($row = fetch_object($friends)){
    $output[] = fetch_assoc($friend_dets);
}
echo json_encode($output);
?>

You can make 1 SQL query for this list, can you tell me whats your table Friends and Profiles info. 您可以对此列表进行1个SQL查询,可以告诉我您的表格朋友和个人资料信息是什么。

In Friends table you must have id to profiles to indicate is the friens of what profile. 在“朋友”表中,您必须具有概要文件的ID,以表明该概要文件的内容。

The query may be like : select profile.* from profile, friends, where friends.id_profile = profile.id and profile.id = current-profile-id 该查询可能类似于:从个人资料,朋友中选择个人资料。*,其中friends.id_profile = profile.id和profile.id = current-profile-id

In your graph you use current profile id in friends table and not profile this may be error 在您的图表中,您使用好友表中的当前个人资料ID,而不是个人资料,这可能是错误的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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