设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2021-02-24 20:15 所属栏目:121 来源:网络整理
导读:public function insert($table,$parameters=[]) { $table = $this-format_table_name($table); $sql = "INSERT INTO $table"; $fields = []; $placeholder = []; foreach ( $parameters as $field=$value){ $place

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类,用单例模式或者用依赖容器来管理较好。

总结

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

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读