成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

PHP使用PDO封裝一個(gè)簡(jiǎn)單易用的DB類

littlelightss / 1036人閱讀

摘要:使用創(chuàng)建測(cè)試庫和表代碼測(cè)試運(yùn)行結(jié)果工具類安裝框架中使用建議在框架中使用類用單例模式或者用依賴容器來管理較好。

使用 創(chuàng)建測(cè)試庫和表
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");
代碼測(cè)試
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"]} 
";
}   

運(yùn)行結(jié)果

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類,用單例模式或者用依賴容器來管理較好。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/23322.html

相關(guān)文章

  • php封裝db 連接sqlite3

    摘要:最新插入的支持?jǐn)?shù)據(jù)庫移植如果你的部署將來有多種數(shù)據(jù)庫那就用它了同時(shí)是設(shè)計(jì)的執(zhí)行效率較高他已經(jīng)封裝為的擴(kuò)展庫組件了運(yùn)行快效率高這是修改為版本的原生類導(dǎo)入的配置文件我這里只是方便前端修改,也可以搞成文件 PDO支持?jǐn)?shù)據(jù)庫移植,如果你的部署將來有多種數(shù)據(jù)庫,那就用它了.同時(shí),PDO是C設(shè)計(jì)的,執(zhí)行效率較高.他已經(jīng)封裝為PHP的擴(kuò)展庫組件了.運(yùn)行快,效率高 class dbManager{ ...

    alin 評(píng)論0 收藏0
  • Laravel 學(xué)習(xí)筆記之 Query Builder 源碼解析(中)

    說明:本篇主要學(xué)習(xí)數(shù)據(jù)庫連接階段和編譯SQL語句部分相關(guān)源碼。實(shí)際上,上篇已經(jīng)聊到Query Builder通過連接工廠類ConnectionFactory構(gòu)造出了MySqlConnection實(shí)例(假設(shè)驅(qū)動(dòng)driver是mysql),在該MySqlConnection中主要有三件利器:IlluminateDatabaseMysqlConnector;IlluminateDatabaseQuery...

    zhou_you 評(píng)論0 收藏0
  • Laravel學(xué)習(xí)筆記之Query Builder源碼解析(上)

    摘要:說明本文主要學(xué)習(xí)模塊的源碼。這里,就已經(jīng)得到了鏈接器實(shí)例了,該中還裝著一個(gè),下文在其使用時(shí)再聊下其具體連接邏輯。 說明:本文主要學(xué)習(xí)Laravel Database模塊的Query Builder源碼。實(shí)際上,Laravel通過Schema Builder來設(shè)計(jì)數(shù)據(jù)庫,通過Query Builder來CURD數(shù)據(jù)庫。Query Builder并不復(fù)雜或神秘,只是在PDO擴(kuò)展的基礎(chǔ)上又開...

    Steve_Wang_ 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<