我想打印出“ forum_question”表的所有内容。
我究竟做错了什么?无论如何,我都会收到消息“没有找到!”,
但是我确信$ db-> connect确实可以工作,所以它必须与query或loadRows函数有关。

这是我的数据库类:

<?php
class Database {
    private $host;
    private $user;
    private $password;
    private $rows;
    private $result;
    private $dbName;
    private $connection;
    private $isReady;

    public function __construct() {
        $this->result = null;
        $this->isReady = false;
        }

        /* setters */
    public function setHost($host){ $this->host = $host; }
    public function setUser($user){ $this->user = $user; }
    public function setPassword($password){ $this->password = $password; }
    public function setDbName($dbName){ $this->dbName = $dbName; }

    /* Interface functions */
    public function initiate($host=null,$user=null,$password=null,$dbName=null) {
        if(isset($host,$user,$password,$dbName)==false) {
            die("Please provide require settings.");
        }
        $this->setHost($host);
        $this->setUser($user);
        $this->setPassword($password);
        $this->setDbName($dbName);
        $this->isReady = true;
    }

    public function connect() {
        if($this->isReady==false) {
            die("Not ready to connect, please initiate connection");
        }
        $connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
        $this->connection = new PDO($connection_string, $this->user, $this->password);
        $this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
    }

    public function disconnect() {
        $this->connection = null;
        $this->isReady = false;
        $this->setHost = null;
        $this->setUser = null;
        $this->setPassword = null;
        $this->setDbName = null;
    }

    public function query($sql) {
        $this->result = $this->connection->query($sql);
    }

    public function countRows() {
        return $this->result->rowCount(); }

    public function loadRows() {
        if(!$this->result) die("Nothing found!");
        $this->rows = array();
        foreach ($this->result as $row) {
            $this->rows[] = $row;
        }
        return $this->rows;
    }

} // End of Database class
?>


这是我的索引文件:

<?php

require_once 'class_database.php';

$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();

$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();


?>

最佳答案

为什么不尝试使用其他连接脚本?例如:

<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
    printf("Connection failed: %s \n", $mysqli->connect_error);
    exit();
}
$mysqli->set_charset("utf8");


工作正常,您要做的就是:

<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();


假设您将连接脚本保存在文件“ connection.php”中。

07-24 17:49