【发布时间】:2014-09-17 17:36:01
【问题描述】:
我对 mysqli 准备语句非常陌生,事实上这是我第一次尝试它。我有这段代码,我在每个命令之间添加了回显,它显示 aaa 和 bbb 但不显示 ccc,我在这里做错了什么?
没有错误出现,只是一个空白屏幕:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT title FROM `in-the-press`")) {
$stmt->execute();
echo 'aaa';
$stmt->bind_result($title);
echo 'bbb';
$result = $stmt->get_result();
echo 'ccc';
while ($stmt->fetch()) {
printf("%s %s\n", $title);
}
echo 'ddd';
$stmt->close();
}
$mysqli->close();
?>
更新通过执行以下操作,我能够使其正常工作:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT id, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($id, $community, $map, $image);
$stmt->fetch();
printf($id . ' ' . $community . ' ' . $map . ' ' . $image);
$stmt->close();
}
?>
但这只给了我 1 行数据,我如何获取所有行数据?
【问题讨论】:
-
当没有变量绑定到查询时,不需要准备好的语句——只需使用
query()。结果集对象(来自query()的返回值或来自准备好的语句get_result()的返回值)可以通过foreach()进行迭代。 stackoverflow.com/a/52323556/2943403