2014-05-13 40 views
0

我有一个简单的表(mgap_orders),其中包含客户订单。多个具有相同的ID(mgap_ska_id),我只想从表中拉出5条记录并显示全部五条记录。显示来自查询的5行数据

我可以通过以下查询和PDO轻松获得一条记录,但是如何显示5行而不是仅显示一行?

$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id"; 

    while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC)) 
    { 
    $item=$row_cat_sub['mgap_item_description']; 
    $item_num=$row_cat_sub['mgap_item_number']; 
    $item_type=$row_cat_sub['mgap_item_type']; 
    $item_cat=$row_cat_sub['mgap_item_catalog_number']; 
    $item_ven=$row_cat_sub['mgap_item_vendor']; 
    $item_pur=$row_cat_sub['mgap_item_percent_purchased']; 
    $item_sales=$row_cat_sub['mgap_item_sales']; 
    } 
+0

使用限制5简单 –

+0

你知道哪5行吗? –

+0

摆脱那个笨蛋GROUP BY – Strawberry

回答

2

使用limit 5然后把结果在一个数组,像这样:

$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5"; 

$items = array(); 

while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC)) 
{ 
    $items['item']  = $row_cat_sub['mgap_item_description']; 
    $items['item_num'] = $row_cat_sub['mgap_item_number']; 
    $items['item_type'] = $row_cat_sub['mgap_item_type']; 
    $items['item_cat'] = $row_cat_sub['mgap_item_catalog_number']; 
    $items['item_ven'] = $row_cat_sub['mgap_item_vendor']; 
    $items['item_pur'] = $row_cat_sub['mgap_item_percent_purchased']; 
    $items['item_sales'] = $row_cat_sub['mgap_item_sales']; 
} 

然后,你可以这样做:

foreach($items as $item) { 
    // echo $item['item'] or whatever 
} 

编辑:或者你可以跳过把它们在数组中只需使用while()即可完成您需要处理的数据。

+1

您可能还想要以有意义的方式对行进行排序(最新的5?按价格?等等) –

+0

@Samsquanch - 感谢您的帮助;像魅力一样工作! – DataGuy