phpoop&;PDO从mysql获取数据
我正在学习OOP和PDO,我为数据库编写了类,为用户编写了类。我编写了注册方法(我想是正确的),所以现在我想获取所有用户的数据,并使用这个公共变量,它们在我的类中phpoop&;PDO从mysql获取数据,php,mysql,database,oop,pdo,Php,Mysql,Database,Oop,Pdo,我正在学习OOP和PDO,我为数据库编写了类,为用户编写了类。我编写了注册方法(我想是正确的),所以现在我想获取所有用户的数据,并使用这个公共变量,它们在我的类中 class Database{ private static $_instance = null; private $_pdo, $_error = false, $_query, $_results, $_count;
class Database{
private static $_instance = null;
private $_pdo,
$_error = false,
$_query,
$_results,
$_count;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.HOST.';dbname='.DBNAME,USERNAME,PASSWORD);
}catch(PDOExeption $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new Database();
}
return self::$_instance;
}
public function query($sql, $params = array()){
$this->_error = false;
$bindParamCounter = 1;
if($this->_query = $this->_pdo->prepare($sql)){
if(count($params)){
foreach ($params as $value) {
$this->_query->bindValue($bindParamCounter, $value);
$bindParamCounter++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}else{
$this->_error = true;
}
}
return $this;
}
public function insert($table, $params = array()){
$paramsCounter = count($params);
if($paramsCounter > 0){
$i = 0;
for($i = 0; $i < $paramsCounter; $i++){
$questionMarks[] = '?';
}
$paramsKeys = implode(', ', array_keys($params));
$questionMarks = implode(', ', $questionMarks);
$sql = 'INSERT INTO '. $table.'('.$paramsKeys.')'." VALUES ({$questionMarks})";
}
return $this->query($sql, $params);
}
public function error(){
return $this->_error;
}
有人能帮我吗?使用您编写的查询方法?您到底遇到了什么问题?你看过PDO库的文档了吗?(例如,像这样)当异常发生时,不要让它轻易消亡。
class Users{
private $_pdo,
$_data,
$_userID,
$_userPassword;
public $id;
public $username;
public $password;
public $firstname;
public $last_name;
public function __construct($user = NULL){
$this->_pdo = Database::getInstance();
}
public function create($params = array()){
try{
$this->_pdo->insert('users', $params);
}catch(PDOExeption $e){
die($e->getMessage());
}
}
public function getAllUsers(){
//get all users
}
}