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

資訊專欄INFORMATION COLUMN

pdo db 操作類

enali / 3037人閱讀

摘要:操作類查詢插入更新刪除簡單數(shù)據(jù)庫操作類構(gòu)造防止克隆查詢語句查詢方式更新表名字段與值條件插入表名字段與值覆蓋方式插入表名字段與值刪除表名條件執(zhí)行語句

1.db操作類

getAll("SELECT * FROM live_userinfo_base limit 10");

/**
 * 插入
 */
//$sss = $db->insert("live_user_online", [
//    "userid" => 1111,
//    "name" => "aaaaaaa",
//    "roomid" => 1006,
//    "role"  => 3,
//    "level" => 3,
//    "ltime" => 21312,
//    "regIp" => 23432432
//]);

/**
 * 更新
 */
//$sss = $db->update("live_user_online", [
//    "name" => "aaaaaaasdfsdfsdfaaaaaaaaaaa",
//    "roomid" => 1006,
//    "role"  => 3,
//    "level" => 3,
//    "ltime" => 21312,
//    "regIp" => 23432432
//], "userid = 1111", false);

/**
 * 刪除
 */
//$sss = $db->delete("live_user_online", "userid = 1111", false);
//print_r($sss);


/**
 * Db 簡單數(shù)據(jù)庫操作類
 */
/**
 * MyPDO
 * @author Jason.Wei 
 * @license http://www.sunbloger.com/
 * @version 5.0 utf8
 */
class Db
{
    protected static $_instance = null;
    protected $dbName = "";
    protected $dsn;
    protected $dbh;

    /**
     * 構(gòu)造
     *
     * @return MyPDO
     */
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        try {
            $this->dsn = "mysql:host=".$dbHost.";dbname=".$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec("SET character_set_connection=".$dbCharset.", character_set_results=".$dbCharset.", character_set_client=binary");
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }

    /**
     * 防止克隆
     *
     */
    private function __clone() {}

    /**
     * Singleton instance
     *
     * @return Object
     */
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }


    public function getOne($strSql, $debug = false)
    {
        return $this->query($strSql, $queryMode = "Row", $debug = false);
    }

    public function getAll($strSql, $debug = false)
    {
        return $this->query($strSql, $queryMode = "All", $debug = false);
    }

    /**
     * Query 查詢
     *
     * @param String $strSql SQL語句
     * @param String $queryMode 查詢方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    private function query($strSql, $queryMode = "All", $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $recordset = $this->dbh->query($strSql);
        $this->getPDOError();
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
            if ($queryMode == "All") {
                $result = $recordset->fetchAll();
            } elseif ($queryMode == "Row") {
                $result = $recordset->fetch();
            }
        } else {
            $result = null;
        }
        return $result;
    }

    /**
     * Update 更新
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段與值
     * @param String $where 條件
     * @param Boolean $debug
     * @return Int
     */
    public function update($table, $arrayDataValue, $where = "", $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        if ($where) {
            $strSql = "";
            foreach ($arrayDataValue as $key => $value) {
                $strSql .= ", `$key`="$value"";
            }
            $strSql = substr($strSql, 1);
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        } else {
            $strSql = "REPLACE INTO `$table` (`".implode("`,`", array_keys($arrayDataValue))."`) VALUES ("".implode("","", $arrayDataValue)."")";
        }
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }

    /**
     * Insert 插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段與值
     * @param Boolean $debug
     * @return Int
     */
    public function insert($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "INSERT INTO `$table` (`".implode("`,`", array_keys($arrayDataValue))."`) VALUES ("".implode("","", $arrayDataValue)."")";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
//        $this->dbh->query($strSql);
        $this->getPDOError();
        return $this->dbh->lastInsertId();
    }

    /**
     * Replace 覆蓋方式插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段與值
     * @param Boolean $debug
     * @return Int
     */
    public function replace($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "REPLACE INTO `$table`(`".implode("`,`", array_keys($arrayDataValue))."`) VALUES ("".implode("","", $arrayDataValue)."")";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }

    /**
     * Delete 刪除
     *
     * @param String $table 表名
     * @param String $where 條件
     * @param Boolean $debug
     * @return Int
     */
    public function delete($table, $where = "", $debug = false)
    {
        if ($where == "") {
            $this->outputError(""WHERE" is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            if ($debug === true) $this->debug($strSql);
            $result = $this->dbh->exec($strSql);
            $this->getPDOError();
            return $result;
        }
    }

    /**
     * execSql 執(zhí)行SQL語句
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }

    /**
     * 獲取字段最大值
     *
     * @param string $table 表名
     * @param string $field_name 字段名
     * @param string $where 條件
     */
    public function getMaxValue($table, $field_name, $where = "", $debug = false)
    {
        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != "") $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, "Row");
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }

    /**
     * 獲取指定列的數(shù)量
     *
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = "", $debug = false)
    {
        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != "") $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, "Row");
        return $arrTemp["NUM"];
    }

    /**
     * 獲取表引擎
     *
     * @param String $dbName 庫名
     * @param String $tableName 表名
     * @param Boolean $debug
     * @return String
     */
    public function getTableEngine($dbName, $tableName)
    {
        $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name="".$tableName.""";
        $arrayTableInfo = $this->query($strSql);
        $this->getPDOError();
        return $arrayTableInfo[0]["Engine"];
    }

    /**
     * beginTransaction 事務(wù)開始
     */
    private function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }

    /**
     * commit 事務(wù)提交
     */
    private function commit()
    {
        $this->dbh->commit();
    }

    /**
     * rollback 事務(wù)回滾
     */
    private function rollback()
    {
        $this->dbh->rollback();
    }

    /**
     * transaction 通過事務(wù)處理多條SQL語句
     * 調(diào)用前需通過getTableEngine判斷表引擎是否支持事務(wù)
     *
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $retval = 1;
        $this->beginTransaction();
        foreach ($arraySql as $strSql) {
            if ($this->execSql($strSql) == 0) $retval = 0;
        }
        if ($retval == 0) {
            $this->rollback();
            return false;
        } else {
            $this->commit();
            return true;
        }
    }

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

    /**
     * checkFields 檢查指定字段是否在指定數(shù)據(jù)表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }

    /**
     * getFields 獲取指定數(shù)據(jù)表中的全部字段名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $this->getPDOError();
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows["Field"];
        }
        return $fields;
    }

    /**
     * getPDOError 捕獲PDO錯(cuò)誤信息
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != "00000") {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }

    /**
     * debug
     *
     * @param mixed $debuginfo
     */
    private function debug($debuginfo)
    {
        var_dump($debuginfo);
        exit();
    }

    /**
     * 輸出錯(cuò)誤信息
     *
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception("MySQL Error: ".$strErrMsg);
    }

    /**
     * destruct 關(guān)閉數(shù)據(jù)庫連接
     */
    public function destruct()
    {
        $this->dbh = null;
    }


    /**
     * 析構(gòu)函數(shù)
     */
    public function __destruct()
    {
        $this->destruct();
    }
}

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

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

相關(guān)文章

  • PHP 數(shù)據(jù)庫操作

    摘要:操作數(shù)據(jù)庫的種形式使用擴(kuò)展類庫推薦使用擴(kuò)展類庫這是類庫的升級版,但已經(jīng)不推薦使用擴(kuò)展包含哪三個(gè)類與區(qū)別可以支持多種數(shù)據(jù)庫,而且操作方法一致只支持?jǐn)?shù)據(jù)庫如何使用連接數(shù)據(jù)庫什么是如何關(guān)閉連接通過來連接數(shù)據(jù)庫,其中必須傳入數(shù)據(jù)源名稱數(shù)據(jù)源名稱是 PHP操作數(shù)據(jù)庫的2種形式 使用 PDO 擴(kuò)展類庫(推薦) 使用 Mysqli 擴(kuò)展類庫(這是Mysql類庫的升級版,但已經(jīng)不推薦使用) PDO...

    Jingbin_ 評論0 收藏0
  • Laravel核心解讀--Database(一)基礎(chǔ)介紹

    摘要:第三步注冊工廠啟動(dòng)數(shù)據(jù)庫服務(wù)數(shù)據(jù)庫服務(wù)的啟動(dòng)主要設(shè)置的連接分析器,讓能夠用服務(wù)連接數(shù)據(jù)庫。 在我們學(xué)習(xí)和使用一個(gè)開發(fā)框架時(shí),無論使用什么框架,如何連接數(shù)據(jù)庫、對數(shù)據(jù)庫進(jìn)行增刪改查都是學(xué)習(xí)的重點(diǎn),在Laravel中我們可以通過兩種方式與數(shù)據(jù)庫進(jìn)行交互: DB, DB是與PHP底層的PDO直接進(jìn)行交互的,通過查詢構(gòu)建器提供了一個(gè)方便的接口來創(chuàng)建及運(yùn)行數(shù)據(jù)庫查詢語句。 Eloquent...

    reclay 評論0 收藏0
  • 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 評論0 收藏0

發(fā)表評論

0條評論

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