加入收藏 | 设为首页 | 会员中心 | 我要投稿 源码网 (https://www.900php.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP用PDO如何封装简单易用的DB类详解

发布时间:2021-02-26 15:48:37 所属栏目:PHP教程 来源:网络整理
导读:副标题#e# 前言 PDO扩展为PHP访问数据库定义了一个轻量级的、一致性的接口,它提供了一个数据访问抽象层,这样,无论使用什么数据库,都可以通过一致的函数执行查询和获取数据。PDO随PHP5.1发行,在PHP5.0的PECL扩展中也可以使用。 我个人理解:PDO是一个抽

public function insert($table,$parameters=[])
{
$table = $this->format_table_name($table);
$sql = "INSERT INTO $table";
$fields = [];
$placeholder = [];
foreach ( $parameters as $field=>$value){
$placeholder[] = ':'.$field;
$fields[] = ''.$field.'';
}
$sql .= '('.implode(",",$fields).') VALUES ('.implode(",$placeholder).')';

$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
$id = $this->dbh->lastInsertId();
if(empty($id)) {
return $this->sth->rowCount();
} else {
return $id;
}
}

public function errorInfo()
{
return $this->sth->errorInfo();
}

protected function format_table_name($table)
{
$parts = explode(".",$table,2);

if(count($parts) > 1) {
$table = $parts[0].".{$parts[1]}";
} else {
$table = "$table";
}
return $table;
}

function errorCode()
{
return $this->sth->errorCode();
}
}

class MySQLException extends Exception { }

框架中使用建议

在框架中使用DB类,用单例模式或者用依赖容器来管理较好。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持

(编辑:源码网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读