Skip to content

Instantly share code, notes, and snippets.

@freretuc
Last active November 28, 2018 20:44
Show Gist options
  • Save freretuc/1259478 to your computer and use it in GitHub Desktop.
Save freretuc/1259478 to your computer and use it in GitHub Desktop.
MySQL / MariaDB PDO + functions
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'bla');
define('DB_PASS', 'bla');
define('DB_BASE', 'bla');
define('DB_CONN', 'mysql:host='.DB_HOST.';dbname='.DB_BASE);
// Buildin singleton class
class mSQL extends PDO {
private static $_instance;
public function __construct () {}
private function __clone () {}
public static function getInstance () {
// Add specific options to the link
$pdo_opts[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8";
$pdo_opts[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
if(!isset(self::$_instance))
self::$_instance = new PDO(DB_CONN, DB_USER, DB_PASS, $pdo_opts);
return self::$_instance;
}
}
function myquery($sql, $data = array()) {
// Try to prepare and run the request
try {
$rs = mSQL::getInstance()->prepare($sql);
if(!$rs->execute($data)) {
die("<pre>ERROR :\n" . $sql);
}
} catch(Exception $ex) {
die("<pre>ERROR :\n" . $sql . "\n" . $ex->getMessage());
}
// Try to get the result
$rows = array();
try {
$rows = $rs->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $ex) {
// do nothing
}
return $rows;
}
function myinsert($table, $data) {
$keys = array();
$values = array();
$params = array();
foreach($data as $_key => $_val) {
$keys[] = " `$_key` ";
$values[] = " :$_key ";
$params[":".$_key] = $_val;
}
myquery("INSERT INTO ".$table." (".implode(',', $keys).") VALUES (".implode(',', $values).") ; ", $params);
return mSQL::getInstance()->lastInsertId();
}
function myupdate($table, $keys, $data) {
$params = array();
// Get the keys
$where = array();
foreach($keys as $_key => $_val) {
$params[":".$_key] = $_val;
$where[] = " `$_key` = :$_key ";
}
// Get the updated values
$update = array();
foreach($data as $_key => $_val) {
$params[":".$_key] = $_val;
$update[] = " `$_key` = :$_key ";
}
// Build and run the query...
myquery("UPDATE $table SET ".implode(",", $update)." WHERE ".implode(" AND ", $where)." ; ", $params);
}
function mydelete($table, $keys) {
$params = array();
// Get the keys
$where = array();
foreach($keys as $_key => $_val) {
$params[":".$_key] = $_val;
$where[] = " `$_key` = :$_key ";
}
// Build and run the query...
myquery("DELETE FROM $table WHERE ".implode(" AND ", $where)." ; ", $params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment