只需添加一个while循环。mysqli_fetch_assoc 返回一行并将内部指针移动到下一行,直到获取所有行,然后返回 false,while 循环将停止
伪语法理解 while
while ( this is true ) {
execute this
}
所以在你的情况下你可以说
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc 和 mysqli_fetch_row 字面上做同样的事情, assoc 为您提供带有结果字段名称的数组作为索引,因此访问起来更简单(使用 fetch_row 时 $row['name'] 而不是 $row[0] )
玩得开心!:)
编辑
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );