简体   繁体   English

如何使用PHP从数据库中获取数据并以适当的方式表示

[英]How to fetch the data from database and represent in a proper way using PHP

I have a database structure : 我有一个数据库结构:

WORK | NAME | USER_ID
  5  | UL7  |  7
  5  | LL5  |  7
  6  | UR9  |  7
  6  | UL7  |  7

i have wrote a function to fetch the data from db which is : 我写了一个函数来从数据库中获取数据:

function fetchRegion($user_id){
  global $mysqli;
  $stmt = $mysqli->prepare("SELECT name,work from region WHERE user_id =?");
  $stmt->bind_param("s",$id);
  $stmt->execute();
  $stmt->bind_result($work,$name);
  while($stmt->fetch()){
  $row[] = array('work'=>$work,'name'=>$name);
  }
  $stmt->close();
  return $row;
  }

Now the problem what i am facing is i want to represent the data as it should display 现在我面临的问题是我想代表应该显示的数据

5 => UL7,LL5 and 6 =>UR9,UL7 5 => UL7,LL5和6 => UR9,UL7

But i am getting an output in an array. 但是我在数组中得到输出。 Now what can be done to represent the data to display in the above format rather in an array. 现在可以做什么来表示要以上述格式而不是数组显示的数据。

Thanks in advance!! 提前致谢!!

You could use the GROUP_CONCAT() function along with GROUP BY in your sql query like this: 您可以在SQL查询中将GROUP_CONCAT()函数与GROUP BY一起使用,如下所示:

SELECT `work`, GROUP_CONCAT(`name`) FROM `region` WHERE `user_id` =? GROUP BY  `name`

Then, the fetched results would be like this: 然后,获取的结果将如下所示:

work | name
------------
5 | UL7,LL5 
6 | UR9,UL7

Hope it helps! 希望能帮助到你!

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

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