简体   繁体   English

PHP从一个到多个表获取数据

[英]php get data from one to many tables

I have 2 tables A & B 我有2张桌子A和B

Table A
       ID             NAME
       1              John
       2              Jack
       3              Mark

Table B
       ID             phone      UserID
       s1             4586         1
       s2             6996         1
       s3             9654         2

they are one to many relation (John has 2 phone on Table 2) 它们是一对多的关系(John在表2上有2个电话)

my sql query 我的SQL查询

$sql = 'SELECT * 
                FROM 
                A 
                Join
                B
                ON
                B.USER_ID = A.ID
                WHERE 
                A.ID=:ID';

my PHP 我的PHP

foreach($vars['GROUPS'] as $row) {


                <tr><th>Name</th><td><?=$row['Name']?></td></tr>
                <tr><th>phone</th><td><?=$row['phone']?></td></tr>


}

I want to show the phones number for this user John name then show all his details from table 2 . 我想显示该用户John名称的电话号码,然后显示表2中的所有他的详细信息。 as it now loop for me 现在为我循环

I do not know if I understand your question right. 我不知道我是否理解你的问题。 From your query you get two rows for the user John, one is "1-John-s1-4586-1" and the other is "1-John-s2-6996-1", right? 从您的查询中,您获得了用户John的两行,一行是“ 1-John-s1-4586-1”,另一行是“ 1-John-s2-6996-1”,对吗? And you want just one row for that user containing both his phone numbers? 您只想为该用户同时包含两个电话号码的一行? Then you could use GROUP_CONCAT: 然后,您可以使用GROUP_CONCAT:

SELECT A.*, GROUP_CONCAT(b.phone) FROM
A INNER JOIN B ON A.id = B.UserID
WHERE A.ID=:ID
GROUP BY A.id

See the MySQL documentation for more options of the GROUP_CONCAT function: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat 有关GROUP_CONCAT函数的更多选项,请参见MySQL文档: http : //dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

For example, you could use ordering or a custom separator. 例如,您可以使用排序或自定义分隔符。

In PHP you could use explode() if you want to iterate over the phone numbers. 在PHP中,如果要遍历电话号码,可以使用explode()。

You have 2 options: 您有2个选择:

  1. Use group_concat() function in sql to concatenate all telephone numbers a user has into a single string and use pretty much the same loop in php as you use now. 在sql中使用group_concat()函数将用户拥有的所有电话号码连接为一个字符串,并在php中使用与您现在使用的几乎相同的循环。

    select a.id, a.name, group_concat(b.phone) as phone from a inner join b on a.id=b.user_id group by a.id, a.name

  2. Leave your current sql query intact, but change the php loop displaying the table. 保留当前的SQL查询不变,但更改显示表的php循环。 In this case only print out a name with all the corresponding phone numbers after looping through all the records returned from the query. 在这种情况下,仅在遍历查询返回的所有记录后才打印出具有所有相应电话号码的名称。 Just concatenate all phone numbers in the loop. 只需串联所有电话号码即可。

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

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