【问题标题】:Fill php array with msql fetch用 sql fetch 填充 php 数组
【发布时间】:2017-01-07 21:32:36
【问题描述】:

我想获取“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.**
    }

【问题讨论】:

    标签: php arrays loops indexing fetch


    【解决方案1】:

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

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

    【讨论】:

    • 如何打印数组中的第二个值?回声 $arr[2] ?
    • 是的,如果您指的是第二行。如果您想要一行中的第二个值,则必须使用$arr[2]['name of the value']。您可以像访问任何其他数组一样访问$arr
    • 值的名称是什么?不能用索引作为变量打印数组吗?我无法使用 echo $arr[$index] 打印我的值
    • 使用print_r($arr[$index]),或在您尝试打印的位置显示代码。
    【解决方案2】:

    不确定我是否理解,但可能是这样的。为列分配别名以使事情变得更容易。

    $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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 2017-12-24
      • 1970-01-01
      • 2012-12-29
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多