以下实例中我们从 myDB 数据库的 MyGuests 表读取了 id, firstname 和 lastname 列的数据并显示在页面上:
以上代码解析如下:
首先,我们设置了 SQL 语句从 MyGuests数据表中读取 id, firstname 和 lastname 三个字段。之后我们使用该 SQL 语句从数据库中取出结果集并赋给复制给变量 $result。
函数 num_rows() 判断返回的数据。
如果返回的是多条数据,函数 fetch_assoc() 将结合集放入到关联数组并循环输出。 while() 循环出结果集,并输出 id, firstname 和 lastname 三个字段值。
以下实例使用 MySQLi 面向过程的方式,效果类似以上代码:
2333
106***5971@qq.com
参考地址
在php 8.1 及以上版本中,直接运行上面的PDO代码会出现类似于:
Return type of TableRows::current() should either be compatible with RecursiveIteratorIterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in xxx
的报错,这是因为新版本的php在从标准库扩展类时,重载函数强制要求添加返回类型。将TableRows类作如下修改即可:
class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); function current(): string { return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>"; function beginChildren(): void { echo "<tr>"; function endChildren(): void { echo "</tr>" . "\n"; }