简体   繁体   中英

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 )

I was expecting 4 entries: 1147, 1152, 1157, 1157. Could someone suggest what I'm doing wrong? presumably fetch_array() doesn't do what I thought.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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