PHP PDO demo

<?php
class DB {

  private $pdo = null;

  public function __construct($host, $database, $user, $password) {
    try {
      $this->pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
    } catch (PDOException $e) {
      echo 'Connect Database Exception:' . $e->getMessage();
    }
  }

  public function findOne($sql, $params = null) {
    $statement = $this->pdo->prepare($sql);
    $statement->execute($params);
    return $statement->fetch(PDO::FETCH_ASSOC);
  }

  public function findAll($sql, $params = null) {
    $statement = $this->pdo->prepare($sql);
    $statement->execute($params);
    return $statement->fetchAll(PDO::FETCH_ASSOC);
  }

  public function findSingle($sql, $params = null) {
     $statement = $this->pdo->prepare($sql);
     $statement->execute($params);
     return $statement->fetchColumn(0);
  }

  public function execute($sql, $params = null) {
    $statement = $this->pdo->prepare($sql);
    return $statement->execute($params);
  }
  
  public function quote($var) {
    return $this->pdo->quote($var);
  }

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

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

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

相关推荐