PHP MySQLI在get_results()中准备语句中断

use*_*240 4 php mysqli

我对mysqli准备好的陈述很新,其实这是我第一次尝试它.我有这个代码块,我把echos放在每个命令之间,它显示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();

?>
Run Code Online (Sandbox Code Playgroud)

更新通过执行以下操作,我能够实现此功能:

<?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();

        }

?>
Run Code Online (Sandbox Code Playgroud)

但这只给我一行数据,如何获取所有数据行?

Bil*_*win 7

要使用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();
    }
Run Code Online (Sandbox Code Playgroud)

如果不使用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();
    }
Run Code Online (Sandbox Code Playgroud)