我对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行数据,如何获得所有数据行?
要使用get_result()
,必须使用mysqlnd驱动程序。PHP 5.4和更高版本默认情况下启用此功能。如果使用的是早期版本的PHP,则必须进行一些安装才能使mysqlnd正常工作。参见http://php.net/manual/en/mysqlnd.install.php
如果使用get_result()
,则不需要绑定任何东西。您只需将每一行作为数组获取,然后将列作为该数组的元素引用:
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps `")) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
printf("%s %s\n", $row["title"], $row["community"]);
}
$stmt->close();
}
如果不使用get_result()
,则以旧方式使用Mysqli,将变量绑定到列,然后调用fetch()
以填充变量。但是您需要运行一个循环,直到fetch()
结果完成后返回NULL。
if ($stmt = $mysqli->prepare("SELECT title, community, map, image FROM `googleMaps`")) {
$stmt->execute();
$stmt->bind_result($title, $community, $map, $image);
while ($stmt->fetch()) {
printf("%s %s\n", $title, $community);
}
$stmt->close();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句