资讯专栏INFORMATION COLUMN

PHP使用PDO封装一个简单易用的DB类

littlelightss / 1033人阅读

摘要:使用创建测试库和表代码测试运行结果工具类安装框架中使用建议在框架中使用类用单例模式或者用依赖容器来管理较好。

使用 创建测试库和表
create database db_test;
CREATE TABLE `user` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` char(11) NOT NULL,
    `created_at` int(10) unsigned NOT NULL,
    PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ("1", "wang", "1501109027");
INSERT INTO `user` VALUES ("2", "meng", "1501109026");
INSERT INTO `user` VALUES ("3", "liu", "1501009027");
INSERT INTO `user` VALUES ("4", "yuan", "1500109027");
代码测试
require __DIR__ . "/DB.php";
$db = new DB();
$db->__setup([
    "dsn"=>"mysql:dbname=db_test;host=localhost",
    "username"=>"root",
    "password"=>"******",
    "charset"=>"utf8"
]);


$user = $db->fetch("SELECT * FROM user where id = :id", ["id" => 1]);
echo $user["name"];
echo "
";

$insertId = $db->insert("user", ["name" => "salamander", "created_at" => time()]);
echo "insert user {$insertId}
";
$users = $db->fetchAll("SELECT * FROM user");
foreach ($users as $item) {
    echo "user {$item["id"]} is {$item["name"]} 
";
}   

运行结果

DB工具类
dsn = $config["dsn"];
        $this->user = $config["username"];
        $this->password = $config["password"];
        $this->charset = $config["charset"];
        $this->connect();
    }

    private function connect()
    {
        if(!$this->dbh){
            $options = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . $this->charset,
            );
            $this->dbh = new PDO($this->dsn, $this->user,
                $this->password, $options);
        }
    }

    public function beginTransaction()
    {
        return $this->dbh->beginTransaction();
    }

    public function inTransaction()
    {
        return $this->dbh->inTransaction();
    }

    public function rollBack()
    {
        return $this->dbh->rollBack();
    }

    public function commit()
    {
        return $this->dbh->commit();
    }

    function watchException($execute_state)
    {
        if(!$execute_state){
            throw new MySQLException("SQL: {$this->lastSQL}
".$this->sth->errorInfo()[2], intval($this->sth->errorCode()));
        }
    }

    public function fetchAll($sql, $parameters=[])
    {
        $result = [];
        $this->lastSQL = $sql;
        $this->sth = $this->dbh->prepare($sql);
        $this->watchException($this->sth->execute($parameters));
        while($result[] = $this->sth->fetch(PDO::FETCH_ASSOC)){ }
        array_pop($result);
        return $result;
    }

    public function fetchColumnAll($sql, $parameters=[], $position=0)
    {
        $result = [];
        $this->lastSQL = $sql;
        $this->sth = $this->dbh->prepare($sql);
        $this->watchException($this->sth->execute($parameters));
        while($result[] = $this->sth->fetch(PDO::FETCH_COLUMN, $position)){ }
        array_pop($result);
        return $result;
    }

    public function exists($sql, $parameters=[])
    {
        $this->lastSQL = $sql;
        $data = $this->fetch($sql, $parameters);
        return !empty($data);
    }

    public function query($sql, $parameters=[])
    {
        $this->lastSQL = $sql;
        $this->sth = $this->dbh->prepare($sql);
        $this->watchException($this->sth->execute($parameters));
        return $this->sth->rowCount();
    }

    public function fetch($sql, $parameters=[], $type=PDO::FETCH_ASSOC)
    {
        $this->lastSQL = $sql;
        $this->sth = $this->dbh->prepare($sql);
        $this->watchException($this->sth->execute($parameters));
        return $this->sth->fetch($type);
    }

    public function fetchColumn($sql, $parameters=[], $position=0)
    {
        $this->lastSQL = $sql;
        $this->sth = $this->dbh->prepare($sql);
        $this->watchException($this->sth->execute($parameters));
        return $this->sth->fetch(PDO::FETCH_COLUMN, $position);
    }

    public function update($table, $parameters=[], $condition=[])
    {
        $table = $this->format_table_name($table);
        $sql = "UPDATE $table SET ";
        $fields = [];
        $pdo_parameters = [];
        foreach ( $parameters as $field=>$value){
            $fields[] = "`".$field."`=:field_".$field;
            $pdo_parameters["field_".$field] = $value;
        }
        $sql .= implode(",", $fields);
        $fields = [];
        $where = "";
        if(is_string($condition)) {
            $where = $condition;
        } else if(is_array($condition)) {
            foreach($condition as $field=>$value){
                $parameters[$field] = $value;
                $fields[] = "`".$field."`=:condition_".$field;
                $pdo_parameters["condition_".$field] = $value;
            }
            $where = implode(" AND ", $fields);
        }
        if(!empty($where)) {
            $sql .= " WHERE ".$where;
        }
        return $this->query($sql, $pdo_parameters);
    }

    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 { }

Composer安装

SimpleDB

框架中使用建议

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/23322.html

相关文章

  • php封装db 连接sqlite3

    摘要:最新插入的支持数据库移植如果你的部署将来有多种数据库那就用它了同时是设计的执行效率较高他已经封装为的扩展库组件了运行快效率高这是修改为版本的原生类导入的配置文件我这里只是方便前端修改,也可以搞成文件 PDO支持数据库移植,如果你的部署将来有多种数据库,那就用它了.同时,PDO是C设计的,执行效率较高.他已经封装为PHP的扩展库组件了.运行快,效率高 class dbManager{ ...

    alin 评论0 收藏0
  • Laravel 学习笔记之 Query Builder 源码解析(中)

    说明:本篇主要学习数据库连接阶段和编译SQL语句部分相关源码。实际上,上篇已经聊到Query Builder通过连接工厂类ConnectionFactory构造出了MySqlConnection实例(假设驱动driver是mysql),在该MySqlConnection中主要有三件利器:IlluminateDatabaseMysqlConnector;IlluminateDatabaseQuery...

    zhou_you 评论0 收藏0
  • Laravel学习笔记之Query Builder源码解析(上)

    摘要:说明本文主要学习模块的源码。这里,就已经得到了链接器实例了,该中还装着一个,下文在其使用时再聊下其具体连接逻辑。 说明:本文主要学习Laravel Database模块的Query Builder源码。实际上,Laravel通过Schema Builder来设计数据库,通过Query Builder来CURD数据库。Query Builder并不复杂或神秘,只是在PDO扩展的基础上又开...

    Steve_Wang_ 评论0 收藏0

发表评论

0条评论

littlelightss

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<