我正试图使用pdo查询数据库,但我无法解决问题。我已经为我的数据库详细信息和服务器详细信息创建了一个init文件,为配置和索引文件和数据库文件创建了配置文件。
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: \axamp\htdocs\Student Management system\index.php第6行
您想要声明对象——只需从对象类的一部分调用实例,就会返回一个不完整的对象部分。调用函数时,就好像它只是一个函数,而不是它作为一个整体是类的一部分,因此,当引用整个类的任何其他部分时,逻辑就会丢失,因为PHP只将其单独视为get
函数。
解决方法:
<?php
require_once 'core/init.php';
//here
$user = new Db();
$userSelect = $user->get('users',array('username', '=' , 'raja' ));
...
由此,$user
就是您的对象。
辛格尔顿
如果您想将连接创建为singleton,那么对类方法(~函数)的每个引用都必须使用singleton语法进行引用——因此,对count()
的引用应该需要使用::
而不是->
重写为singleton语法。
请阅读http://www.phptherightway.com/pages/Design-Patterns.html