Skip to content

Instantly share code, notes, and snippets.

@faejr
Last active April 19, 2018 09:25
Show Gist options
  • Save faejr/ee5a3047089cd9662287e1c857f89acd to your computer and use it in GitHub Desktop.
Save faejr/ee5a3047089cd9662287e1c857f89acd to your computer and use it in GitHub Desktop.
idk
<?php
abstract class Database
{
protected $db;
protected $query;
protected $values = [];
public function __construct($dbname, $host, $username, $password) { }
abstract public function query($sql, $values);
abstract public function select($table, $columns);
abstract public function update($table);
abstract public function with($columnValues);
abstract public function where($column, $operator, $value);
abstract protected function execute();
abstract protected function staticType($value);
}
<?php
class Database_Pdo extends Database {
public function __construct($dbname, $host, $username, $password)
{
$this->db = new PDO("mysql:dbname={$dbname};host={$host};charset=utf8", $username, $password);
}
public function query($sql, $values = [])
{
$statement = $this->db->prepare($sql);
$statement->execute($values);
if($statement->rowCount() === 1) return $statement->fetch(PDO::FETCH_OBJ);
if($statement->rowCount() > 1) return $statement->fetchAll(PDO::FETCH_OBJ);
return false;
}
public function select($table, $columns = [])
{
if(count($columns) > 0) {
$column = implode(',', $columns);
} else {
$column = '*';
}
$this->query = "SELECT {$column} FROM {$table} ";
return $this;
}
public function update($table)
{
$this->query = "UPDATE {$table} ";
return $this;
}
public function with($columnValues = [])
{
$this->query .= "SET ";
foreach($columnValues as $column => $value)
{
$this->query .= "{$column} = ?, ";
$this->values[] = $value;
}
$this->query .= 'updated_at = NOW()';
return $this;
}
public function where($column, $operator, $value)
{
$this->query .= " WHERE {$column} {$operator} ?";
$this->values[] = $value;
return $this->execute();
}
protected function execute()
{
return $this->query($this->query, $this->values);
}
protected function staticType($value)
{
$value = is_int($value) ? (int) $value : $value;
$value = is_string($value) ? '"' . $value . '"' : $value;
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment