【发布时间】:2015-09-14 02:51:46
【问题描述】:
我正在尝试使用 pdo 查询数据库,但我无法找出问题所在。我为我的数据库详细信息和服务器详细信息创建了一个初始化文件,并为配置和索引文件和数据库文件创建了配置文件。
index.php
<?php
require_once 'core/init.php';
$user = Db::getInstance()->get('users',array('username', '=' , 'raja' ));
if($user->count())
{
echo "No user";
}
else{
echo "OK!";
}
?>
Db.php
<?php
class Db
{
private static $_instance = null;
private $_pdo,
$_query,
$_error=false,
$_results,
$_count=0;
private function __construct()
{
try
{
$this->_pdo =new PDO("mysql:host=" .Config::get('mysql/host') . ";dbname=" .Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if (!isset(self::$_instance))
{
self::$_instance = new Db();
}
return self::$_instance;
}
public function query($sql,$params=array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x=1;
if (count($params))
{
foreach ($params as $param )
{
$this->_query->bindValue($x,$param);
$x++;
}
}
if ($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->error=true;
}
}
return $this;
}
public function action($action,$table,$where=array())
{
if(count($where) === 3)
{
$operators = array('=','<','>','>=','<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator,$operators))
{
$sql = "{$action}FROM{$table} WHERE {$field} {$operator} ?";
if($this->query($sql,array($value))->error()){
return $this;
}
}
}
return false;
}
public function get($table,$where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table,$where)
{
return $this->action('DELETE ', $table,$where);
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
}
?>
它报告一个关于找不到count 对象的致命错误:
致命错误:在非对象上调用成员函数 count() C:\xampp\htdocs\Student Management system\index.php 在第 6 行
【问题讨论】:
-
您的 index.php 中是否包含 Db.php 文件?
-
错误信息很清楚,
$user是一个非对象。调试 $user 并查看它是否是一个对象,实际上它确实定义了count方法。我会说,马上查询失败 -
@SuryaJothika ,嗨,这不是 Java 自动包含类而不指定其文件。
-
如果类不包括在内,你会得到一个
Class not found致命错误 -
如果您要创建一个单例类,请尝试将您的
__construct()公开并使其将$this返回到像if(!isset(self::$singleton)) self::$singleton = $this; return self::$singleton;这样的静态变量。然后你可以做$con = new Db();,在包含你的PDO连接的__construct里面有一个protected function connect()。只是我的两分钱。