Classe Database con PDO

Classe Database con PDO

Pubblicato il 26/05/2023

Un semplice script da utilizzare per interrogare un Database, con tutte le funzioni per selezionare, inserire, modificare e rimuovere record.



class Database extends PDO{
  public function __construct(){
    $DB_TYPE = 'mysql';
    $DB_HOST = HOST_DB;
    $DB_NAME = NOME_DB;
    $DB_USER = UTENTE_DB;
    $DB_PASS = PSW_DB;
    parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);
  }

  public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC){
    $sth = $this--->prepare($sql);
    foreach ($array as $key => $value) {
      $sth->bindValue("$key", $value);
    }
    if(!$sth->execute()){
      $this->handleError();
    }else{
      return $sth->fetchAll($fetchMode);
    }
  }

  public function insert($table, $data){
    ksort($data);
    $fieldNames = implode('`, `', array_keys($data));
    $fieldValues = ':' . implode(', :', array_keys($data));
    $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");
    foreach ($data as $key => $value) {
      $sth->bindValue(":$key", $value);
    }
    if(!$sth->execute()){
      $this->handleError();
      return 'ko';
    }else{
      return 'ok';
    }
  }

  public function update($table, $data, $where){
    ksort($data);
    $fieldDetails = NULL;
    foreach($data as $key=> $value) {
      $fieldDetails .= "`$key`=:$key,";
    }
    $fieldDetails = rtrim($fieldDetails, ',');
    $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
    foreach ($data as $key => $value) {
      $sth->bindValue(":$key", $value);
    }
    $sth->execute();
    if(!$sth->execute()){
      $this->handleError();
      return 'ko';
    }else{
      return 'ok';
    }
  }

  public function delete($table, $where, $limit = 1){
    $this->exec("DELETE FROM $table WHERE $where LIMIT $limit");
    return 'ok';
  }

  public function rowsCount($table){
    $sth = $this->prepare("SELECT * FROM ".$table);
    $sth->execute();
    return $sth -> rowCount();
  }

  private function handleError(){
    if ($this->errorCode() != '00000'){
      if ($this->_errorLog == true) echo json_encode($this->errorInfo());
      throw new Exception("Error: " . implode(',', $this->errorInfo()));
    }
  }
	
}

Categoria: PHP Script

Condividi sui Social: