16

我有以下代码:

include $_SERVER['DOCUMENT_ROOT'].'/include/conn.php'; 

$query = "SELECT title FROM news_event";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);
$row_cnt = $result->num_rows;
$result->free();
$mysqli->close();

如果只有一个结果,这很好,因为我可以回显$row['title']但是如果有很多结果,我如何让它循环并打印每一行?

我确信这真的很简单,但我只是不确定我需要在 Google 中搜索什么。

我正在寻找mysqli类似的东西:

while( $row = mysql_fetch_array($result) )
{
    echo $row['FirstName'] . " " . $row['LastName'];
    echo "<br />";
}
4

4 回答 4

28

只需将其替换为mysqli_fetch_arrayor mysqli_result::fetch_array:)

while( $row = $result->fetch_array() )
{
    echo $row['FirstName'] . " " . $row['LastName'];
    echo "<br />";
}

几乎所有mysql_*的功能都有对应的mysqli_*功能。

于 2012-09-28T20:46:46.043 回答
8

简单的mysqli解决方案:

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT * FROM table WHERE 1');
while ( $rows = $resource->fetch_assoc() ) {
    print_r($rows);//echo "{$row['field']}";
}
$resource->free();
$db->close();

错误处理:如果出现致命错误,脚本将终止并显示错误消息。

// ini_set('display_errors',1); // Uncomment to show errors to the end user.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
    echo "{$row['field']}";
}
$resource->free();
$db->close();

使用迭代器: PHP 5.4 添加了支持

$db = new mysqli('localhost','user','password','database');
foreach ( $db->query('SELECT * FROM table') as $row ) {
    print_r($row);//echo "{$row['field']}";
}
$db->close();

获取单个记录:此代码不需要循环。

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
于 2015-11-19T01:34:07.893 回答
4

利用:

while ($row = $result->fetch_array(MYSQLI_BOTH)) {
    // Look inside $row here, do what you want with it.
}

查看这里的关联数组示例(也应与 fetch_array() 版本对应):

http://php.net/manual/en/mysqli-result.fetch-assoc.php

于 2012-09-28T20:49:32.550 回答
1

您可以简单地循环使用foreach

$query = "SELECT title FROM news_event";
$result = $mysqli->query($query);
foreach($result as $row) {
    echo $row['FirstName'] . " " . $row['LastName'];
    echo "<br />";
}

如果您想将 mysqli 代码和 HTML 分开,那么最好将所有内容提取到一个数组中并稍后循环。

$query = "SELECT title FROM news_event";
$result = $mysqli->query($query);
$news_events = $result->fetch_all(MYSQLI_ASSOC);

// Later in HTML:    

<div>
<?php foreach($news_events as $row): ?>
    <p><?= $row['FirstName'] ?> <?= $row['LastName'] ?></p>
<?php endforeach ?>
</div>
于 2020-03-06T13:02:40.570 回答