Skip to content

Instantly share code, notes, and snippets.

@Sixl-Daniel
Last active March 4, 2019 20:47
Show Gist options
  • Save Sixl-Daniel/8b1b35c2a6cdc149f048d02448aab14f to your computer and use it in GitHub Desktop.
Save Sixl-Daniel/8b1b35c2a6cdc149f048d02448aab14f to your computer and use it in GitHub Desktop.
PDO
<?php
class Database {
private $db;
private $statement;
// private $error;
private $optionsPDO = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET lc_time_names='de_DE', NAMES utf8mb4"
];
public function __construct(){
$config = parse_ini_file("config/db.ini");
$dsn = 'mysql:host='.$config['host'].';port='.$config['port'].';dbname='.$config['db'].';charset='.$config['charset'];
try {
$this->db = new PDO($dsn, $config['user'], $config['pass'], $this->optionsPDO);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
}
public function query($sql) {
$this->statement = $this->db->prepare($sql);
}
public function bind($param, $value, $type = null) {
if(is_null($type)){
switch(true){
case is_int($value): $type = PDO::PARAM_INT; break;
case is_bool($value): $type = PDO::PARAM_BOOL; break;
case is_null($value): $type = PDO::PARAM_NULL; break;
default: $type = PDO::PARAM_STR;
}
}
$this->statement->bindValue($param, $value, $type);
}
public function execute() {
return $this->statement->execute();
}
public function getData() {
$this->execute();
return $this->statement->fetchAll();
}
public function lastInsertId() {
return $this->db->lastInsertId();
}
public function close() {
$this->db = null;
}
/* general purpose query function, without type-hinted binding */
function run($sql, $params = NULL) {
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
host = 'localhost';
db = 'database';
user = 'root';
pass = '';
charset = 'utf8mb4';
port = '3306';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment