PDO 最好的地方在于它是面向对象的。因此,保持这种形式并充分利用它,我们可以创建一个 PDO CRUD 类来处理所有数据库查询等。
这是一个示例,可以添加自定义方法/功能以增强功能等:
<?php
Class PDO_CRUD{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
/*Raw Select*/
public function rawQuery($sql){
$this->connect();
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
public function get($table,$fieldname=null, $id=null){
$this->connect();
$sql = "SELECT * FROM $table WHERE $fieldname = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
/*Insert*/
public function put($table,$values){
$this->connect();
$fieldnames = array_keys($values[0]);
$sql = "INSERT INTO $table ";
$fields = '('.implode(' ,', $fieldnames).')';
$bound = '(:'.implode(', :', $fieldnames).')';
$sql .= $fields.' VALUES '.$bound;
$statement = $this->db->prepare($sql);
foreach($values as $vals){
$statement->execute($vals);
}
}
/*Update*/
public function update($table,$fieldname, $value, $pk, $id){
$this->connect();
$sql = "UPDATE $table SET $fieldname = :value WHERE $pk = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->bindParam(':value', $value, PDO::PARAM_STR);
$statement->execute();
}
/*Update Hits*/
public function add_hit($table,$id){
$this->connect();
$sql = "UPDATE $table SET hits = hits + 1 WHERE url = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
}
/*Delete*/
public function delete($table,$id){
$this->connect();
$sql = "DELETE FROM $table WHERE url = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
}
}
//Then we have a nice way to access all our querys from one class.
//ini the model class
$model = new PDO_CRUD('localhost','yourDB','User','Password');
$insert = array(array('id'=>NULL,'somecol'=>'someval'));
$model->put('someTable',$insert);
//multiple inserts
$insert = array(array('id'=>NULL,'somecol'=>'someval123'),
array('id'=>NULL,'somecol'=>'someval1234'),
array('id'=>NULL,'somecol'=>'someval12345'));
$model->put('someTable',$insert);
//or delete a row
$model->delete('someTable',1);
//or a raw query
$model->rawQuery('DELETE FROM someTable');
?>