我有一个表格“ orders”,其中保存了网站上的所有订单。它通过以下方式保存数据:

ID | Session_id | image | item | extra | customer_name


样品日期

 12 | sdgfafjhsf | image1.jpg | coffee | milk | roger
 13 | sdgfafjhsf | image1.jpg | muffin | jam  | roger
 14 | fjgjgsdfjg | image3.jpg | coffee | none | John


目前,我有PHP访问数据库并一一列出所有清单。

 mysql_connect("localhost", "root", "") or die(mysql_error()) ;
 mysql_select_db("store") or die(mysql_error()) ;

 //Retrieves data from MySQL
 $data = mysql_query("SELECT * FROM orders WHERE status ='ordered'") or die(mysql_error());  //Puts it into an array
 while($info = mysql_fetch_array( $data ))
 {

 //Outputs the image and other data

 Echo "$info[customer_name] <img src='cameras/$info[image]'/>  : $info[item] with $info[extras] <br />";


 }


理想情况下,我希望数据按会话ID分组。因此,它将一次打印出客户的姓名和图像,然后再打印与之关联的所有项目。

例如。罗杰,咖啡,牛奶,松饼,果酱

有任何想法吗?
谢谢!

最佳答案

一种简单的方法是对SQL进行排序,以使您可以从每个会话中获取彼此相邻的所有条目,并且只需记住您获取的最后一个会话ID,即可知道是否应输出名称和图片。这是一些伪代码来说明我的意思;

$data =
  mysql_query("SELECT * FROM orders WHERE status ='ordered' ORDER BY session_id")
                or die(mysql_error());

$last_session_id = "**DUMMY**";  // Set a dummy value to not match the first row

while($info = mysql_fetch_array( $data ))
{
  if($info['session_id'] != $last_session_id)
  {
    //Outputs the image and other data if a new session_id has been found
    echo "$info[customer_name] <img src='cameras/$info[image]'/>  : $info[item] with $info[extras] <br />";
    $last_session_id = $info['session_id'];
  } else {
    // Same session_id as last row, skip name and picture
    echo "$info[item] with $info[extras] <br />";
  }
}


附带说明,不建议使用mysql_*数据库API,而应考虑使用mysqlipdo

关于php - 用相同ID的PHP组合MySQL行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16955849/

10-12 12:35
查看更多