php mysqli_fetch_array仅返回一个结果

ctrmrzij  于 2023-02-21  发布在  PHP
关注(0)|答案(3)|浏览(171)

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

$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

在那个专栏里有几所大学的例子,所以我不知道我做错了什么。

d5vmydt9

d5vmydt91#

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

wn9m85ua2#

如果要从结果集中读取所有行,则必须使用mysqli_fetch_all()而不是mysqli_fetch_array()
将您的代码替换为:

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

ukxgm1gy3#

mysqli_fetch_array($result)只从数据库中获取一个值。因此使用$row = mysqli_fetch_all($result,MYSQLI_ASSOC)代替$row = mysqli_fetch_array($result)
打印_r($行);

相关问题