简体   繁体   English

使用mysqli将列值存储在数组中

[英]Store column values in array with mysqli

I'm trying to collect the column values into an array so I can then get an average of all the values. 我正在尝试将列值收集到一个数组中,这样我就可以获取所有值的平均值。 Here's my code so far: 到目前为止,这是我的代码:

    $conn = new mysqli($hn, $un, $pw, $db);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$average_hdpe = "SELECT hdpe FROM $region";
$average_hdpe_result = $conn->query($average_hdpe) or die(mysqli_error($conn)) ;
$average_hdpe_array = $average_hdpe_result->fetch_array();

print_r($average_hdpe_array);

running the above code prints: 运行上面的代码打印:

Array ( [0] => 1147 [hdpe] => 1147 ) 数组([0] => 1147 [hdpe] => 1147)

I was expecting 4 entries: 1147, 1152, 1157, 1157. Could someone suggest what I'm doing wrong? 我原本希望有4个条目:1147、1152、1157、1157。有人可以建议我做错了什么吗? presumably fetch_array() doesn't do what I thought. 大概fetch_array()并没有实现我的想法。

  $average_hdpe = "SELECT hdpe FROM $region";
    $average_hdpe_result = $conn->query($average_hdpe) or die(mysqli_error($conn)) ;
     $array = array();//create empty array
     while($row = $average_hdpe_result->fetch_array()){//loop to get all results
         $array[] = $row;//grab everything and store inside array
     }
print_r($array);//this should give you everything

Create a array store the fetched data in the array 创建一个数组,将获取的数据存储在数组中

$conn = new mysqli($hn, $un, $pw, $db);
/* check connection */
if ($conn->connect_error) {
    printf("Connect failed: %s\n", $conn->connect_error);
exit();
}

$average_hdpe = "SELECT hdpe FROM $region";
$average_hdpe_result = $conn->query($average_hdpe) or die() ;
$average_hdpe_array = array();
while($row = $average_hdpe_result->fetch_assoc()){
$average_hdpe_array[] = $row;
}

print_r($average_hdpe_array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM