使用msql fetch填充php数组

时间:2016-08-31 10:28:46

标签: php arrays loops indexing fetch

我想得到" till.code"值并使用增量数字索引数组保存它们。 我的想法是,我可以使用" $ array [$ variable],$ array [$ variable] .. etc"打印这些值。变量应该是数字,1,2,3 ..

 $stmt2=$dbh->prepare("SELECT till.code,shop.description Collate Cyrillic_General_CI_AI as description, count(tra.id) as servicios,ROUND(sum(tra.total_amount),1) as facturacion
          FROM [TCPOS4].[dbo].[transactions] as tra, [TCPOS4].[dbo].[tills] as till,[TCPOS4].[dbo].[shops] as shop where tra.till_id=till.id and shop.id=till.shop_id  and convert(date,tra.trans_date) = '$name2' and '$usuari'=CAST(LEFT(shop.code,5) AS INT) group by till.code,shop.description order by code;");

    $stmt2->execute();
    while ($row = $stmt2->fetch()) {
         **I have to fill this.**
    }

2 个答案:

答案 0 :(得分:1)

简单的方法,可能不是最好的方式,但取决于场景将是:

$index = 1;
$arr = array();
while ($row = $stmt2->fetch()) {
     $arr[ $index ] = $row;
     $index++;
}

答案 1 :(得分:0)

不确定我是否理解但也许是这样的。为列分配别名以简化操作。

$stmt2=$dbh->prepare("SELECT 
                        till.code as 'code',
                        shop.description Collate Cyrillic_General_CI_AI as 'description', 
                        count(tra.id) as 'servicios',
                        ROUND(sum(tra.total_amount),1) as 'facturacion'
                    FROM
                        [TCPOS4].[dbo].[transactions] as tra, 
                        [TCPOS4].[dbo].[tills] as till,
                        [TCPOS4].[dbo].[shops] as shop 
                    WHERE tra.till_id=till.id
                            and shop.id=till.shop_id 
                            and convert(date,tra.trans_date) = '$name2' 
                            and '$usuari'=CAST(LEFT(shop.code,5) AS INT) 
                    GROUP BY till.code,shop.description
                    ORDER BY code;");

    $stmt2->execute();
    $output=array();
    while( $row = $stmt2->fetch() )$output[]=$row->code;