Skip to content

Instantly share code, notes, and snippets.

@Satwa Satwa/Database.php
Created Jan 18, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.