PHPのPDO共通クラスライブラリインスタンス分析

13943 ワード

この例では、PHPのPDO共通クラスライブラリについて説明します.皆さんの参考にしてください.具体的には以下の通りです.
1、Db.class.php接続データベース

setAttribute(PDO::ATTR_PERSISTENT, true); //             
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //       
      $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); //             SQL   NULL
      $pdo->query('SET NAMES utf8'); //        
    } catch (PDOException $e) {
      exit('       ,    :'. $e->getMessage());
    }
    return $pdo;
  }
}
?>


2、Model.class.phpデータベース操作クラス

_db = Db::getDB();
  }
  /**
   *        
   * @param string $tName   
   * @param array $field     
   * @param array $val    
   * @param bool $is_lastInsertId       ID
   * @return int         ,$is_lastInsertId  true,    ID
   */
  public function insert($tName, $fields, $vals, $is_lastInsertId=FALSE) {
    try {
      if (!is_array($fields) || !is_array($vals))
        exit($this->getError(__FUNCTION__, __LINE__));
      $fields = $this->formatArr($fields);
      $vals = $this->formatArr($vals, false);
      $tName = $this->formatTabName($tName);
      $this->_sql = "INSERT INTO {$tName} ({$fields}) VALUES ({$vals})";
      if (!$is_lastInsertId) {
        $row = $this->_db->exec($this->_sql);
        return $row;
      } else {
        $this->_db->exec($this->_sql);
        $lastId = (int)$this->_db->lastInsertId();
        return $lastId;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *        
   * @param string $tName   
   * @param array $field     
   * @param array $val    
   * @param string $condition   
   * @return int       
   */
  public function update($tName, $fieldVal, $condition) {
    try {
      if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $upStr = '';
      foreach ($fieldVal as $k=>$v) {
        $upStr .= '`'.$k . '`=' . '\'' . $v . '\'' . ',';
      }
      $upStr = rtrim($upStr, ',');
      $this->_sql = "UPDATE {$tName} SET {$upStr} WHERE {$condition}";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *        ( :     where   )
   * @param string $tName   
   * @param string $condition   
   * @return int       
   */
  public function del($tName, $condition) {
    try {
      if (!is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName= $this->formatTabName($tName);
      $this->_sql = "DELETE FROM {$tName} WHERE {$condition}";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *       
   * @param string $tName   
   * @param string $condition   
   * @return int
   */
  public function total($tName, $condition='') {
    try {
      if (!is_string($tName))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName}" .
      ($condition=='' ? '' : ' WHERE ' . $condition);
      $re = $this->_db->query($this->_sql);
      foreach ($re as $v) {
        $total = $v['total'];
      }
      return (int)$total;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *          
   * @param string $tName   
   * @param string $field     
   * @param array $ids     
   * @return int       
   */
  public function delMulti($tName, $field, $ids) {
    try {
      if (!is_string($tName) || !is_array($ids))
        exit($this->getError(__FUNCTION__, __LINE__));
      $delStr = '';
      $tName = $this->formatTabName($tName);
      $field = $this->formatTabName($field);
      foreach ($ids as $v) {
        $delStr .= $v . ',';
      }
      $delStr = rtrim($delStr, ',');
      $this->_sql = "DELETE FROM {$tName} WHERE {$field} IN ({$delStr})";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *          ( :   INT   )
   * @param string $tName   
   * @return int
   */
  public function insertId($tName) {
    try {
      if (!is_string($tName))
        exit($this->getError(__FUNCTION__, __LINE__));
      $this->_sql = "SHOW TABLE STATUS LIKE '{$tName}'";
      $result = $this->_db->query($this->_sql);
      $insert_id = 0;
      foreach ($result as $v) {
        $insert_id = $v['Auto_increment'];
      }
      return (int)$insert_id;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *           (    )
   * @param string $tName   
   * @param string $field      
   * @return bool
   */
  public function exists($tName, $condition) {
    try {
      if (!is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}";
      $result = $this->_db->query($this->_sql);
      foreach ($result as $v) {
         $b = $v['total'];
      }
      if ($b) {
        return true;
      } else {
        return false;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *           (   INT   )
   * @param string $tName   
   * @param string $primary   
   * @param int $id    
   * @return bool
   */
  public function existsByPK($tName, $primary, $id) {
    try {
      if (!is_string($tName) || !is_string($primary)
      || !is_int($id))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id;
      $result = $this->_db->query($this->_sql);
      foreach ($result as $v) {
         $b = $v['total'];
      }
      if ($b) {
        return true;
      } else {
        return false;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *      ( :      INT   ,    )
   * @param string $tName   
   * @param string $primary     
   * @param int or array or string $ids          INT,    array,        string
   * @return int         
   */
  public function delByPK($tName, $primary, $ids, $mult=FALSE) {
    try {
      if (!is_string($tName) || !is_string($primary)
      || (!is_int($ids) && !is_array($ids) && !is_string($ids))
      || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $stmt = $this->_db->prepare("DELETE FROM {$tName} WHERE {$primary}=?");
      if (!$mult) {
        $stmt->bindParam(1, $ids);
        $row = $stmt->execute();
      } else {
        if (is_array($ids)) {
          $row = 0;
          foreach ($ids as $v) {
            $stmt->bindParam(1, $v);
            if ($stmt->execute()) {
              $row++;
            }
          }
        } elseif (is_string($ids)) {
          if (!strpos($ids, '-'))
            exit($this->getError(__FUNCTION__, __LINE__));
          $split = explode('-', $ids);
          if (count($split)!=2 || $split[0]>$split[1])
            exit($this->getError(__FUNCTION__, __LINE__));
          $i = null;
          $count = $split[1]-$split[0]+1;
          for ($i=0; $i_sql ="DELETE FROM {$tName} WHERE {$primary} in ({$idStr})";
          $row = $this->_db->exec($this->_sql);
        }
      }
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *              
   * @param string $tName   
   * @param string $condition   
   * @param string or array $fields      ,   *
   * @return string || array
   */
  public function getRow($tName, $condition='', $fields="*") {
    try {
      if (!is_string($tName) || !is_string($condition)
      || !is_string($fields) || empty($fields))
         exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT {$fields} FROM {$tName} ";
      $this->_sql .= ($condition=='' ? '' : "WHERE {$condition}") . " LIMIT 1";
      $sth = $this->_db->prepare($this->_sql);
      $sth->execute();
      $result = $sth->fetch(PDO::FETCH_ASSOC);
      if ($fields === '*') {
        return $result;
      } else {
        return $result[$fields];
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *       
   * @param string $tName   
   * @param string $fields     ,   *
   * @param string $condition   
   * @param string $order   
   * @param string $limit     
   * @return PDOStatement
   */
  public function getAll($tName, $fields='*', $condition='', $order='', $limit='') {
    try {
      if (!is_string($tName) || !is_string($fields)
      || !is_string($condition) || !is_string($order)
      || !is_string($limit))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $fields = ($fields=='*' || $fields=='') ? '*' : $fields;
      $condition = $condition=='' ? '' : " WHERE ". $condition ;
      $order = $order=='' ? '' : " ORDER BY ". $order;
      $limit = $limit=='' ? '' : " LIMIT ". $limit;
      $this->_sql = "SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}";
      $sth = $this->_db->prepare($this->_sql);
      $sth->execute();
      $result = $sth->fetchAll(PDO::FETCH_ASSOC);
      return $result;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   *      (     )
   * @param array $field
   * @param bool $isField
   * @return string
   */
  private function formatArr($field, $isField=TRUE) {
    if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__));
    $fields = '';
    if ($isField) {
      foreach ($field as $v) {
        $fields .= '`'.$v.'`,';
      }
    } else {
      foreach ($field as $v) {
        $fields .= '\''.$v.'\''.',';
      }
    }
    $fields = rtrim($fields, ',');
    return $fields;
  }
  /**
   *      
   * @param int $count   
   * @return string           
   */
  private function formatMark($count) {
    $str = '';
    if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__));
    if ($count==1) return '?';
    for ($i=0; $i' . $fun . '() line'. $line .' ERROR!';
  }
  /**
   *     
   * @param string $tName
   * @return string
   */
  private function formatTabName($tName) {
    return '`' . trim($tName, '`') . '`';
  }
  /**
   *     
   */
  public function __destruct() {
    $this->_db = null;
  }
}


PHPについてもっと兴味のある読者は、「php curl用法総括」、「PHP演算と演算子用法総括」、「PHPネットワークプログラミングテクニック総括」、「PHP基本文法入門教程」、「php操作officeドキュメントテクニック総括(word,excel,access,pptを含む)」、「php日付と时间用法総括」、「phpオブジェクト向けプログラム設計入門チュートリアル」、「php文字列(string)用法総括」、「php+mysqlデータベース操作入門チュートリアル」および「php一般データベース操作テクニック要約」
ここで述べたことが皆さんのPHPプログラム設計に役立つことを願っています.