只需添加一个while循环。 mysqli_fetch_assoc返回行和内部指针移动到下一行,直到所有行被提取,则返回假,while循环将停止
伪语法来理解,而
while (this is true) {
execute this
}
因此,对你的情况可以说
while ($row = mysqli_fetch_assoc($result)) {
// process/output $row
}
mysqli_fetch_assoc和mysqli_fetch_row字面上做的一样,assoc命令将让你与你的结果字段名的数组索引,所以这是简单的存取($行[“名称”]而不是$行[0]当使用fetch_row时)
玩得开心! :)
编辑
// 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);
您的图片不工作。看看'while'循环。 – Kermit
您缺少$ with numberOfFieds = mysqli_num_fields($ result);并且请在echo''您的代码'后面和结尾处添加'单引号'';或者你已经看到我的答案... –