XBackBone/app/Database/DB.php

66 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2018-04-28 12:20:07 +00:00
<?php
namespace App\Database;
use PDO;
class DB
{
2019-11-20 17:49:31 +00:00
/** @var DB */
protected static $instance;
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
/** @var PDO */
protected $pdo;
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
/** @var string */
protected $currentDriver;
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
public function __construct(string $dsn, string $username = null, string $password = null)
{
$this->pdo = new PDO($dsn, $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
$this->currentDriver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($this->currentDriver === 'sqlite') {
$this->pdo->exec('PRAGMA foreign_keys = ON');
}
}
2018-04-28 12:20:07 +00:00
2019-11-21 17:00:47 +00:00
public function query(string $query, $parameters = [])
2019-11-20 17:49:31 +00:00
{
if (!is_array($parameters)) {
2019-11-21 17:00:47 +00:00
$parameters = [$parameters];
2019-11-20 17:49:31 +00:00
}
$query = $this->pdo->prepare($query);
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
foreach ($parameters as $index => $parameter) {
$query->bindValue($index + 1, $parameter, is_int($parameter) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
2019-11-20 17:49:31 +00:00
$query->execute();
2019-11-20 17:49:31 +00:00
return $query;
}
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
/**
* Get the PDO instance.
*
* @return PDO
*/
public function getPdo(): PDO
{
return $this->pdo;
}
2018-04-28 12:20:07 +00:00
2019-11-20 17:49:31 +00:00
/**
* Get the current PDO driver.
*
* @return string
*/
public function getCurrentDriver(): string
{
return $this->currentDriver;
}
}