我正在尝试使用类在 php 中使用 PDO。
所以我定义了一个这样的配置文件
<?php
global $configVars;
$configVars['online'] = false;
if(($_SERVER['SERVER_NAME'])!='localhost' and ($_SERVER['SERVER_NAME'])!='abc')
{
$configVars['dbhost'] = "localhost";
$configVars['dbuser'] = "dbuser";
$configVars['dbpassword'] = "dbpass";
$configVars['dbname'] = "dbname";
}
?>
然后我定义了连接数据库的类
<?php
class dbClass{
var $dbHost,
$dbUser,
$dbName,
$dbPass,
$dbTable,
$dbLink,
$resResult,
$dbh,
$dbPort;
function dbClass(){
global $configVars;
$this->dbHost = $configVars['dbhost'];
$this->dbUser = $configVars['dbuser'];
$this->dbPass = $configVars['dbpassword'];
$this->dbName = $configVars['dbname'];
$this->connect_PDO();
}
function connect_PDO(){
try {
$dbh = new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName.'', $this->dbUser, $this->dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected.";
}
catch(PDOException $e) {
echo "I'm sorry Charlie, I'm afraid i cant do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
$dbh = null;
}
}
}
?>
现在我已经定义了另一个类来从表中选择记录
<?
class cms extends dbClass
{
function get_rec($id=0)
{
($id==0?$addQuery="":$addQuery=" where id =".$id);
$statement = $dbh->prepare("select * from TABLENAME :name order by id");
$statement->execute(array(':name' => $addQuery));
$row = $statement->fetchAll();
return $row ;
}
}
?>
现在当我像这样在我的 PHP 文件中使用这个函数时
<?php
$objCMS=new cms();
$getCMS=$objCMS->get_rec(1);
echo $getCMS[0];
?>
我得到了关注
Connected.
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs
我试图从过去 2 天解决这个问题,但没有成功。
我是 PDO 的新手,想使用它。
谢谢