在单个变量中存储多列之和

时间:2019-01-20 05:46:31

标签: php mysqli

这是我的代码。

$sql = "SELECT sum(col_1) as col_1_sum FROM table_1";
        $run = mysqli_query($conn, $sql);
        while($rows = mysqli_fetch_assoc($run)){
            $col[1] = $rows['col_1_sum'];
        }

我想知道最有效的方法是获取多9个列的总和并将它们分别存储在不同的变量中, 就像$ col [2]中第二行的总和,等等。

2 个答案:

答案 0 :(得分:0)

像这样更改您的sql

$sql = "SELECT sum(col_1) as col_1_sum ,sum(col_2) as col_2_sum, sum(col_3) as col_3_sum  FROM table_1";

并获取

while($rows = mysqli_fetch_assoc($run)){
            $col[1] = $rows['col_1_sum']; // in here its better to start this $col[] array's index from 0 
            $col[2] = $rows['col_2_sum'];
            $col[3] = $rows['col_3_sum'];
        }

或者像这样的$ col数组从第0个索引开始

while($rows = mysqli_fetch_assoc($run)){
                $col[0] = $rows['col_1_sum']; // in here its better to start this $col[] array's index from 0 
                $col[1] = $rows['col_2_sum'];
                $col[2] = $rows['col_3_sum'];
            }

答案 1 :(得分:0)

我想使用2D数组将其保留为单个变量

$variable[row_index][col_index] = $rows[col_index];