Skip to content

Instantly share code, notes, and snippets.

@kanduvisla
Last active September 26, 2015 05:47
Show Gist options
  • Save kanduvisla/1048803 to your computer and use it in GitHub Desktop.
Save kanduvisla/1048803 to your computer and use it in GitHub Desktop.
Simple Database class
<?php
/**
* Simple database class
* (c) 2012
* Author: Giel Berkers
* Date: 5-3-12
* Time: 14:24
*/
class Db
{
/**
* @var PDO
*/
private $pdo;
private static $instance;
private function __construct(){}
private function instance()
{
if(!self::$instance) {
self::$instance = new Db();
}
return self::$instance;
}
/**
* Connect to database
* @param $database
* @param $username
* @param $password
* @param string $host
*/
public static function connect($database, $username, $password, $host = 'localhost')
{
self::instance()->pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database, $username, $password);
}
/**
* Run a query
* @param $sql
* @param int $fetchStyle
* @return resource
*/
public static function mq($sql, $fetchStyle = PDO::FETCH_ASSOC) {
$result = self::instance()->pdo->query($sql)->fetch($fetchStyle);
return $result;
}
/**
* @param $sql
* @return PDOStatement
*/
public static function sql($sql) {
$result = self::instance()->pdo->query($sql);
return $result;
}
/**
* Get an associated array
* @param $sql
* @return array
*/
public static function ma($sql) {
$result = self::instance()->mq($sql);
return $result[0];
}
/**
* Get a single result
* @param $sql
* @return mixed
*/
public static function sr($sql) {
$result = self::instance()->pdo->query($sql)->fetchColumn(0);
return $result;
}
/**
* Insert or update automatically if the key/value check exists or not
* @param $key
* @param $value
* @param array $values
* @param $table
*/
public static function insertOrUpdate($key, $value, $values = array(), $table)
{
if(!empty($key) && !empty($values))
{
if(self::sr(
sprintf('SELECT COUNT(*) AS total FROM %1$s WHERE %2$s = \'%3$s\';',
$table, $key, $value)
) >= 1) {
// Update
$statements = array();
foreach($values as $k => $v) {
$statements[] = $k . ' = \''. $v .'\'';
}
self::mq(
sprintf('UPDATE %1$s SET %2$s WHERE %3$s = \'%4$s\';',
$table, implode(',', $statements), $key, $value)
);
} else {
// New
self::mq(
sprintf('INSERT INTO %1$s (%2$s) VALUES (\'%3$s\');',
$table, implode(',', array_keys($values)), implode('\', \'', $values))
);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment