我试图使用以下代码(在$ host中使用适当的值等)对小型mysql数据库进行非常非常简单的查询:
$connection = mysqli_connect($host, $user_name, $password, $database);
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$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_close($connection);
如您所见,我以人类可读的方式打印出结果,产生:
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
该专栏中有一些示例大学,所以我不确定我做错了什么。
答案 0 :(得分:5)
想象一下以下
$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);
答案 1 :(得分:0)
如果要从结果集中获取所有行,则必须使用 mysqli_fetch_all()
而不是 mysqli_fetch_array()
。
用这个替换你的代码:
$result = mysqli_query($connection, "select university from universities_alpha");
$rows = mysqli_fetch_all($result, MYSQLI_BOTH);