【发布时间】:2020-10-04 03:42:52
【问题描述】:
我尝试使用数据库查询创建登录/注册系统。我是 PHP OOP 的新手。我有带代码的 DB.php 类
class DB{
protected 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'));
echo 'Connected';
} catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance;
}
return self::$instance;
}
public function query($sql, $params=array()){
$this->_error = false;
if($this->_query= $this->_pdo->prepare($sql)){
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;
}
private 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(){
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
public function error(){
return $this->_error;
}
}
?>
和 index.php 类似
<?php
require_once('core/init.php');
$user = DB::getInstance()->get('users', array('username','-','alex'));
if($user->error()){
echo 'No user';
} else {
echo 'OK!';
}
?>
我得到一个致命错误:未捕获的错误:在 C:\xampp\htdocs\RegisterSystem\index.php:4 中调用 null 上的成员函数 get() 堆栈跟踪:#0 {main} 在 C 中抛出: \xampp\htdocs\RegisterSystem\index.php 在第 4 行 有人可以帮帮我吗?
【问题讨论】:
-
if(!isset(self::$instance)){ self::$instance; }可能是一件好事,如果它尚未设置 mh?