php中pdo封装类,php 封装PDO类

//数据库连接类,不建议直接使用DB,而是对DB封装一层

//这个类不会被污染,不会被直接调用

class DB {

//pdo对象

private $_pdo = null;

//用于存放实例化的对象

static private $_instance = null;

//公共静态方法获取实例化的对象

static protected function getInstance() {

if (!(self::$_instance instanceof self)) {

self::$_instance = new self();

}

return self::$_instance;

}

//私有克隆

private function __clone() {}

//私有构造

private function __construct() {

try {

$this->_pdo = new PDO(DB_DNS, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.DB_CHARSET));

$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

exit($e->getMessage());

}

}

//新增

protected function add($_tables, Array $_addData) {

$_addFields = array();

$_addValues = array();

foreach ($_addData as $_key=>$_value) {

$_addFields[] = $_key;

$_addValues[] = $_value;

}

$_addFields = implode(',', $_addFields);

$_addValues = implode("','", $_addValues);

$_sql = "INSERT INTO $_tables[0] ($_addFields) VALUES ('$_addValues')";

return $this->execute($_sql)->rowCount();

}

//修改

protected function update($_tables, Array $_param, Array $_updateData) {

$_where = $_setData = '';

foreach ($_param as $_key=>$_value) {

$_where .= $_value.' AND ';

}

$_where = 'WHERE '.substr($_where, 0, -4);

foreach ($_updateData as $_key=>$_value) {

if (Validate::isArray($_value)) {

$_setData .= "$_key=$_value[0],";

} else {

$_setData .= "$_key='$_value',";

}

}

$_setData = substr($_setData, 0, -1);

$_sql = "UPDATE $_tables[0] SET $_setData $_where";

return $this->execute($_sql)->rowCount();

}

//验证一条数据

protected function isOne($_tables, Array $_param) {

$_where = '';

foreach ($_param as $_key=>$_value) {

$_where .=$_value.' AND ';

}

$_where = 'WHERE '.substr($_where, 0, -4);

$_sql = "SELECT id FROM $_tables[0] $_where LIMIT 1";

return $this->execute($_sql)->rowCount();

}

//删除

protected function delete($_tables, Array $_param) {

$_where = '';

foreach ($_param as $_key=>$_value) {

$_where .= $_value.' AND ';

}

$_where = 'WHERE '.substr($_where, 0, -4);

$_sql = "DELETE FROM $_tables[0] $_where LIMIT 1";

return $this->execute($_sql)->rowCount();

}

//查询

protected function select($_tables, Array $_fileld, Array $_param = array()) {

$_limit = $_order = $_where = $_like = '';

if (Validate::isArray($_param) && !Validate::isNullArray($_param)) {

$_limit = isset($_param['limit']) ? 'LIMIT '.$_param['limit'] : '';

$_order = isset($_param['order']) ? 'ORDER BY '.$_param['order'] : '';

if (isset($_param['where'])) {

foreach ($_param['where'] as $_key=>$_value) {

$_where .= $_value.' AND ';

}

$_where = 'WHERE '.substr($_where, 0, -4);

}

if (isset($_param['like'])) {

foreach ($_param['like'] as $_key=>$_value) {

$_like = "WHERE $_key LIKE '%$_value%'";

}

}

}

$_selectFields = implode(',', $_fileld);

$_table = isset($_tables[1]) ? $_tables[0].','.$_tables[1] : $_tables[0];

$_sql = "SELECT $_selectFields FROM $_table $_where $_like $_order $_limit";

$_stmt = $this->execute($_sql);

$_result = array();

while (!!$_objs = $_stmt->fetchObject()) {

$_result[] = $_objs;

}

return Tool::setHtmlString($_result);

}

//总记录

protected function total($_tables, Array $_param = array()) {

$_where = '';

if (isset($_param['where'])) {

foreach ($_param['where'] as $_key=>$_value) {

$_where .= $_value.' AND ';

}

$_where = 'WHERE '.substr($_where, 0, -4);

}

$_sql = "SELECT COUNT(*) as count FROM $_tables[0] $_where";

$_stmt = $this->execute($_sql);

return $_stmt->fetchObject()->count;

}

//得到下一个ID

protected function nextId($_tables) {

$_sql = "SHOW TABLE STATUS LIKE '$_tables[0]'";

$_stmt = $this->execute($_sql);

return $_stmt->fetchObject()->Auto_increment;

}

//执行SQL

private function execute($_sql) {

try {

$_stmt = $this->_pdo->prepare($_sql);

$_stmt->execute();

} catch (PDOException $e) {

exit('SQL语句:'.$_sql.'
错误信息:'.$e->getMessage());

}

return $_stmt;

}

}

?>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 PHP PDO 封装的示例: ```php class Database { private $host = "localhost"; private $user = "username"; private $password = "password"; private $database = "database"; private $charset = "utf8mb4"; private $pdo; public function __construct() { $dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->charset}"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $this->pdo = new PDO($dsn, $this->user, $this->password, $options); } public function query($sql, $params = []) { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt; } public function fetchAll($sql, $params = []) { $stmt = $this->query($sql, $params); return $stmt->fetchAll(); } public function fetch($sql, $params = []) { $stmt = $this->query($sql, $params); return $stmt->fetch(); } public function insert($table, $data) { $keys = array_keys($data); $values = array_values($data); $placeholders = implode(',', array_fill(0, count($values), '?')); $sql = "INSERT INTO $table (" . implode(',', $keys) . ") VALUES ($placeholders)"; $this->query($sql, $values); return $this->pdo->lastInsertId(); } public function update($table, $data, $where) { $set = []; $values = []; foreach ($data as $key => $value) { $set[] = "$key = ?"; $values[] = $value; } $sql = "UPDATE $table SET " . implode(',', $set) . " WHERE $where"; return $this->query($sql, $values)->rowCount(); } public function delete($table, $where) { $sql = "DELETE FROM $table WHERE $where"; return $this->query($sql)->rowCount(); } } ``` 这个封装PDO,包含了常用的查询操作,如 query、fetchAll、fetch,以及增删改操作,如 insert、update、delete。你可以根据自己的需要进行扩展。使用时,只需要实例化这个,并调用相应的方法即可。例如: ```php $db = new Database(); $rows = $db->fetchAll("SELECT * FROM table WHERE id = ?", [1]); ``` 这个示例会查询一个 ID 为 1 的记录,并返回一个数组。你可以根据需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值