Skip to content

Instantly share code, notes, and snippets.

@anytizer
Last active April 22, 2020 01:33
Show Gist options
  • Save anytizer/a34019c2a90cf0f2b2f672930fa38991 to your computer and use it in GitHub Desktop.
Save anytizer/a34019c2a90cf0f2b2f672930fa38991 to your computer and use it in GitHub Desktop.
Object Oriented PDO MySQL Example
<?php
header("Content-Type: text/plain; charset=utf-8");
ini_set("default_charset", "UTF-8");
mb_internal_encoding("UTF-8");
mb_http_output("UTF-8");
abstract class database
{
protected $pdo = null;
public function __construct()
{
if(null == $this->pdo)
{
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", "root", "", $opt);
$this->pdo->exec("SET NAMES utf8mb4;");
}
}
public function rows($sql="", $data=array())
{
$statement = $this->pdo->prepare($sql);
$statement->execute($data);
$rows = $statement->fetchAll();
return $rows;
}
public function row($sql="", $data=array())
{
$rows = $this->rows($sql, $data);
return $rows[0]??array();
}
}
class timer extends database
{
public function time()
{
$time = $this->row("SELECT DATE_ADD(NOW(), INTERVAL :days DAY) f;", [
":days" => 7
]);
return $time["f"];
}
}
$timer = new timer();
$time = $timer->time();
echo $time;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment