我正在尝试使用PDO从表中检索数据,但我似乎无法向浏览器输出任何内容,我只是得到了一个纯白色的页面。

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

        $lastIndex = 2;

        $sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
        $sth = $conn->prepare($sql);
        $sth->execute(array(':lastIndex' => $lastIndex));

        $c = 1;
        while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
            echo 'ALL STYLING ETC RESULTS HERE';
        $c++;
        }

  $conn = null;        // Disconnect
}

最佳答案

例子。
这是你的dbc类

<?php

class dbc {

    public $dbserver = 'server';
    public $dbusername = 'user';
    public $dbpassword = 'pass';
    public $dbname = 'db';

    function openDb() {
        try {
            $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
        } catch (PDOException $e) {
            die("error, please try again");
        }
        return $db;
    }

    function getAllData($qty) {
        //prepared query to prevent SQL injections
        $query = "select * from TABLE where qty = ?";
        $stmt = $this->openDb()->prepare($query);
        $stmt->bindValue(1, $qty, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $rows;
    }
?>

你的PHP页面:
<?php
require "dbc.php";

$getList = $db->getAllData(25);

foreach ($getList as $key=> $row) {
         echo $row['columnName'] .' key: '. $key;
    }

10-07 14:01