用于显示所有行的 mysqli 查询结果

2022-08-30 22:55:04

我有以下代码:

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 />";
}

答案 1

只需将其替换为或:)mysqli_fetch_arraymysqli_result::fetch_array

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

几乎所有函数都有相应的函数。mysql_*mysqli_*


答案 2

简单的 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();

推荐