【问题标题】:Store column values in array with mysqli使用 mysqli 将列值存储在数组中
【发布时间】:2017-05-16 10:13:13
【问题描述】:

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

    $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() 没有按照我的想法做。

【问题讨论】:

  • 您只获取第一行。尝试使用fetch_all() 而不是fetch_array(),或者保留fetch_array() 并循环结果。这些功能的手册有很好的例子。 (您还会获得双精度值,因为它同时获取数字和关联,您可以 fetch_assoc() 获取关联)。
  • 你混淆了过程和面向对象的方法
  • 为什么不使用 SELECT AVG(hdpe) FROM $region ?

标签: php mysql arrays mysqli


【解决方案1】:
  $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

【讨论】:

    【解决方案2】:

    创建一个数组,将取出的数据存储在数组中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      相关资源
      最近更新 更多