【问题标题】:mysqli_fetch_array returning only one resultmysqli_fetch_array 只返回一个结果
【发布时间】:2014-10-16 23:31:32
【问题描述】:

我正在尝试使用以下代码(在 $host 中使用适当的值等)对小型 mysql 数据库进行非常非常简单的查询:

$result = mysqli_query($connection, "select university from universities_alpha");
$row = mysqli_fetch_array($result);

echo print_r($result);
echo '<br><br>';
echo print_r($row);

如您所见,我以人类可读的方式打印出结果,产生:

mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => Array ( [0] => 19 ) [num_rows] => 9 [type] => 0 ) 1

Array ( [0] => Arizona State Univ. [university] => Arizona State Univ. ) 1

该专栏中有一些示例大学,所以我不确定我做错了什么。

【问题讨论】:

  • 阅读 mysqli 函数的手册。您将fetch_array 放在while 循环中,因为它会一一返回行,直到它返回null 并且循环终止。

标签: php mysqli


【解决方案1】:

mysqli_fetch_array 每次调用时都通过指针工作

想象一下

$result = mysqli_query($connection, "select university from universities_alpha");
$row = mysqli_fetch_array($result); // this is the first row
$row = mysqli_fetch_array($result); // now it's the second row
$row = mysqli_fetch_array($result); // third row

要以您想要的方式实际显示数据,我建议您执行以下操作

$rows = array();
$result = mysqli_query($connection, "select university from universities_alpha");
while($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

print_r($rows);

【讨论】:

    【解决方案2】:

    如果要从结果集中获取所有行,则必须使用 mysqli_fetch_all() 而不是 mysqli_fetch_array()

    用这个替换你的代码:

    $result = mysqli_query($connection, "select university from universities_alpha");
    $rows = mysqli_fetch_all($result, MYSQLI_BOTH);
    

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 2016-05-23
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多