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

时间:2017-05-16 10:13:14

标签: php mysql arrays mysqli

我试图将列值收集到一个数组中,这样我就可以获得所有值的平均值。到目前为止,这是我的代码:

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

运行上面的代码打印:

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

我期待4个参赛作品:1147,1152,1157,1157。 有人可以建议我做错了什么吗?大概fetch_array()并没有按照我的想法行事。

2 个答案:

答案 0 :(得分:2)

  $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

答案 1 :(得分:1)

创建数组存储数组中的读取数据

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