
226
|
第
9
章
数据库
$db = new mysqli("localhost", "petermac", "1q2w3e9i8u7y", "library");
$sql = "SELECT a.name, b.title FROM books b, authors a WHERE
a.authorid=b.authorid";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
echo "{$row['name']} is the author of: {$row['title']}<br />";
}
$result->close();
$db->close();
这里,我们使用
query()
方法调用,将返回的信息存储到变量
$result
中。然后使用结
果对象的方法
fetch_assoc()
,每次提供一行数据,并把这一行数据存储在变量
$row
中。
当结果集中还有行要处理时会继续执行。在
while
循环中,将内容输出到浏览器窗口中。
最后,关闭结果集和数据库对象。
输出内容如下所示
:
J.R.R. Tolkien is the author of: The Two Towers
J.R.R. Tolkien is the author of: The Return of The King
J.R.R. Tolkien is the author of: The Hobbit
Alex Haley is the author ...