Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Satwa
Created January 18, 2019 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Satwa/cfc90dd5541ff7772245a0ec0c2bb04b to your computer and use it in GitHub Desktop.
Save Satwa/cfc90dd5541ff7772245a0ec0c2bb04b to your computer and use it in GitHub Desktop.
PHP Database lib
<?php
class Database{
function __construct(){
try{
$this->pdo = new PDO('sqlite:storage.db'); // can be MySQL too
$this->pdo->query("SET NAMES 'utf8'");
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo "<h1>Impossible de se connecter.</h1>";
die();
}
}
function exec($req, $val = []){ // Insert/Update/Delete
$pdo = $this->pdo;
$sql = $pdo->prepare($req);
foreach($val as $key => $value){
$sql->bindValue(":".$key, $value);
}
$sql->execute();
return $pdo->lastInsertId();
}
function query($req, $val = []){ // query once
$pdo = $this->pdo;
$sql = $pdo->prepare($req);
foreach($val as $key => $value){
$sql->bindValue(":".$key, $value);
}
$sql->execute();
$f = $sql->fetch();
return $f;
}
function queryAll($req, $val = []){ // query all
$pdo = $this->pdo;
$sql = $pdo->prepare($req);
foreach($val as $key => $value){
$sql->bindValue(":".$key, $value);
}
$sql->execute();
$f = $sql->fetchAll();
return $f;
}
function rowCount($req, $val = []){ // get row count
$pdo = $this->pdo;
$sql = $pdo->prepare($req);
foreach($val as $key => $value){
$sql->bindValue(":".$key, $value);
}
$sql->execute();
$c = $sql->rowCount();
return $c;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment