我在这里遵循了这个教程:http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/并编写了以下课程。
database.class.php
<?php
require_once './dbconfig.inc.php';
/**
* MySQL Database PDO Wrapper Class.
*/
class Database {
private $db_host = DB_HOST;
private $db_user = DB_USER;
private $db_name = DB_NAME;
private $db_pass = DB_PASS;
private $dbh;
private $error;
private $stmt;
public function __construct() {
$dsn = 'mysql:host=' . $this->db_host . ';dbname=' . $this->db_name;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though
);
try {
$dbh = new PDO($dsn, $this->db_user, $this->db_pass, $options);
} catch (PDOException $ex) {
$this->error = $ex->getMessage();
echo $this->error;
}
}
public function query($sql) {
$this->stmt = $this->dbh->prepare($sql);
}
public function bind($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute() {
return $this->stmt->execute();
}
public function getRows() {
$this->execute();
$this->stmt->fetchAll();
}
public function getRow() {
$this->execute();
$this->stmt->fetch();
}
public function rowCount() {
return $this->stmt->rowCount();
}
}
dbconfig.inc.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_NAME', 'hms');
define('DB_PASS', 'root');
demo.php
<?php
require_once './database.class.php';
$db = new Database();
$db->query('SELECT * FROM appointment');
$result = $db->getRows();
print_r($result);
连接成功但demo.php没有显示任何内容。在Chrome上,它返回500内部服务器错误。我在CentOS上运行LAMP堆栈中的脚本。我的数据库服务器是MariaDB 5.5
非常感谢任何有关其不起作用的反馈。
答案 0 :(得分:1)
@Philipp是对的。你应该return
来自函数。
所以如果提供你肯定需要:
public function getRows() {
$this->execute();
return $this->stmt->fetchAll();
}
检查@ Fred-ii-评论: require_once&#39; ./ database.class.php&#39 ;;但你声称你的文件是 dbclass.inc.php - 我称之为&#34;文件未找到&#34;。
更新在此处更改:
public function getError() {
return $this->error ;
}
public function __construct() {
$dsn = 'mysql:host=' . $this->db_host . ';dbname=' . $this->db_name;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though
);
try {
$this->dbh = new PDO($dsn, $this->db_user, $this->db_pass, $options);
$this->error = 'ok';
} catch (PDOException $ex) {
$this->error = $ex->getMessage();
}
}
并在demo.php
中更改为:
$db = new Database()
if (($err = $db->getError())=='ok') {
...
} else {
echo $err;
}