我想打印出“forum_question”表的所有内容。我究竟做错了什么?无论如何,我都会收到消息“Nothing found!”,但我确信 $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();
?>