pdo公共類別的定義與用法如何用PHP來實現?

黄舟
發布: 2023-03-14 10:48:01
原創
891 人瀏覽過

這篇文章主要介紹了php實現的pdo公共類別定義與用法,結合具體實例形式分析了php實現的pdo操作類別定義及查詢、插入等使用技巧,需要的朋友可以參考下

本文實例講述了php實作的pdo公共類別定義與用法。分享給大家供大家參考,具體如下:

db.class.php :


#
dsn = 'mysql:host=' . $dbHost . ';dbname=' . $dbName;
      $this->dbh = new \PDO($this->dsn, $dbUser, $dbPasswd);
      $this->dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
      $this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      $this->dbh->exec('SET character_set_connection='.$dbCharset.';SET character_set_client='.$dbCharset.';SET character_set_results='.$dbCharset);
    } catch (Exception $e) {
      $this->outputError($e->getMessage()); 
    }
  }
  public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset='utf8') {
    if (self::$_instance === null) {
      self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
    }
    return self::$_instance;
  }
  public function fetchAll($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        return $stm->fetchAll(\PDO::FETCH_ASSOC);
      }
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function fetchOne($sql, $params = array()) {
    try {
      $result = false;
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        $result = $stm->fetch(\PDO::FETCH_ASSOC);
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function fetchColumn($sql, $params = array()) {
    $result = '';
    try {
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        $result = $stm->fetchColumn();
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function insert($table, $params = array(), $returnLastId = true) {
    $_implode_field = '';
    $fields = array_keys($params);
    $_implode_field = implode(',', $fields);
    $_implode_value = '';
    foreach ($fields as $value) {
      $_implode_value .= ':'. $value.',';
    }
    $_implode_value = trim($_implode_value, ',');
    $sql = 'INSERT INTO ' . $table . '(' . $_implode_field . ') VALUES ('.$_implode_value.')';
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      if ( $returnLastId ) {
        $result = $this->dbh->lastInsertId();
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function update($table, $params = array(), $where = null) {
    $_implode_field = '';
    $_implode_field_arr = array();
    if ( empty($where) ) {
      return false;
    }
    $fields = array_keys($params);
    foreach ($fields as $key) {
      $_implode_field_arr[] = $key . '=' . ':'.$key;
    }
    $_implode_field = implode(',', $_implode_field_arr);
    $sql = 'UPDATE ' . $table . ' SET ' . $_implode_field . ' WHERE ' . $where;
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function delete($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function exec($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  private function outputError($strErrMsg) {
    throw new Exception("MySQL Error: " . $strErrMsg);
  }
  public function __destruct() {
    $this->dbh = null;
  }
}
登入後複製

實例:


 12,);
$res = $pdo->fetchOne($sql, $parame);
var_dump($res);
$sql = 'SELECT * FROM cms_link';
$result = $db->fetchAll($sql);
print_r($result);
//查询记录数量
$sql = 'SELECT COUNT(*) FROM cms_link';
$count = $db->fetchColumn($sql);
echo $count;
$data = array(
  'siteid' => 1,
  'linktype' => 1,
  'name' => 'google',
  'url' => 'http://www.google.com',
  'listorder' => 0,
  'elite' => 0,
  'passed' => 1,
  'addtime' => time()
  );
$lastInsertId = $db->insert('cms_link', $data);
echo $lastInsertId;
//用 try
 try {
     $result = $pdo->insert('news', $essay);
   } catch (Exception $e) {
     error_log($e->getMessage());
     error_log($e->getMessage() . ' in ' . __FILE__ . ' on line ' . __LINE__);
     saveLog('url文章 : ' . $essay['link'] . '  数据插入失败
'); continue; } $data = array( 'siteid' => 1, 'linktype' => 1, 'name' => 'google', 'url' => 'http://www.google.com', 'listorder' => 0, 'elite' => 0, 'passed' => 1, 'addtime' => time() ); $db->insert('cms_link', $data); $sql = 'DELETE FROM cms_link WHERE linkid=4'; $result = $db->delete($sql); var_dump($result);
登入後複製

以上是pdo公共類別的定義與用法如何用PHP來實現?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!