320 lines
6.0 KiB
PHP
Executable File
320 lines
6.0 KiB
PHP
Executable File
<?php
|
||
class DB
|
||
{
|
||
public static $dsn = '';
|
||
public static $user = '';
|
||
public static $pass = '';
|
||
public static $type = '';
|
||
|
||
public static $path = '';
|
||
/**
|
||
* Объект PDO.
|
||
*/
|
||
public static $dbh = null;
|
||
|
||
/**
|
||
* Statement Handle.
|
||
*/
|
||
public static $sth = null;
|
||
|
||
/**
|
||
* Выполняемый SQL запрос.
|
||
*/
|
||
public static $query = '';
|
||
|
||
/**
|
||
* Подключение к БД.
|
||
* $this -> conn = new PDO( 'sqlite:' . $_SERVER['DOCUMENT_ROOT'] . '/bd/'. $bd );
|
||
*/
|
||
public static function getDbh(){
|
||
if (self::$type==''){
|
||
require 'set/' . $_SERVER['SERVER_NAME'] . '.php';
|
||
//self::$type=@$db['type'];
|
||
if (@$db['type']=='mysql'){
|
||
self::$dsn=$db['type'] . ':dbname=' . $db['db'] . ';host=' . $db['host'];
|
||
self::$user=$db['user'];
|
||
self::$pass=$db['password'];
|
||
if (!self::$dbh) {
|
||
try {
|
||
self::$dbh = new PDO(
|
||
self::$dsn,
|
||
self::$user,
|
||
self::$pass,
|
||
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
|
||
);
|
||
self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
|
||
} catch (PDOException $e) {exit('Error connecting to database: ' . $e->getMessage());}
|
||
}
|
||
}
|
||
if (@$db['type']=='sqlite3'){
|
||
# echo "lite";
|
||
if (!self::$dbh) {
|
||
try {
|
||
self::$dbh = new PDO('sqlite:' . 'bd/'. $_SERVER['SERVER_NAME'] . '.db' );
|
||
//Делаем бекап БД
|
||
if (!file_exists('bd/' . date("Y-m-d") . '_'. $_SERVER['SERVER_NAME'] . '.zip'))exec ('zip bd/' . date("Y-m-d") . '_'. $_SERVER['SERVER_NAME'] . '.zip bd/'. $_SERVER['SERVER_NAME'] . '.db 9 &');
|
||
} catch (PDOException $e) {exit('Error connecting to database: ' . $e->getMessage());}
|
||
}
|
||
}
|
||
}else{
|
||
self::$dbh = new PDO('sqlite:' . self::$path );
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
return self::$dbh;
|
||
}
|
||
|
||
/**
|
||
* Закрытие соединения.
|
||
*/
|
||
public static function destroy(){
|
||
self::$dbh = null;
|
||
return self::$dbh;
|
||
}
|
||
|
||
/**
|
||
* Получение ошибки запроса.
|
||
*/
|
||
public static function getError(){
|
||
$info = self::$sth->errorInfo();
|
||
return (isset($info[2])) ? 'SQL: ' . $info[2] : null;
|
||
}
|
||
|
||
/**
|
||
* Возвращает структуру таблицы в виде ассоциативного массива.
|
||
*/
|
||
public static function getStructure($table){
|
||
$res = array();
|
||
foreach (self::getAll("SHOW COLUMNS FROM {$table}") as $row) {$res[$row['Field']] = (is_null($row['Default'])) ? '' : $row['Default'];}
|
||
return $res;
|
||
}
|
||
|
||
/**
|
||
* Добавление в таблицу, в случаи успеха вернет вставленный ID, иначе 0.
|
||
*/
|
||
public static function add($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
return (self::$sth->execute((array) $param)) ? self::getDbh()->lastInsertId() : 0;
|
||
}
|
||
|
||
/**
|
||
* Выполнение запроса.
|
||
*/
|
||
public static function set($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
return self::$sth->execute((array) $param);
|
||
}
|
||
|
||
|
||
/**
|
||
* Получение строки из таблицы.
|
||
*/
|
||
public static function getRow($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
self::$sth->execute((array) $param);
|
||
return self::$sth->fetch(PDO::FETCH_ASSOC);
|
||
}
|
||
|
||
/**
|
||
* Получение всех строк из таблицы.
|
||
*/
|
||
public static function getAll($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
self::$sth->execute((array) $param);
|
||
return self::$sth->fetchAll(PDO::FETCH_ASSOC);
|
||
}
|
||
|
||
/**
|
||
* Получение значения.
|
||
*/
|
||
public static function getValue($query, $param = array(), $default = null){
|
||
$result = self::getRow($query, $param);
|
||
if (!empty($result)) {$result = array_shift($result);}
|
||
return (empty($result)) ? $default : $result;
|
||
}
|
||
|
||
/**
|
||
* Получение столбца таблицы.
|
||
*/
|
||
public static function getColumn($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
self::$sth->execute((array) $param);
|
||
return self::$sth->fetchAll(PDO::FETCH_COLUMN);
|
||
}
|
||
|
||
|
||
|
||
public static function alterTable($query, $param = array()){
|
||
self::$sth = self::getDbh()->prepare($query);
|
||
self::$dbh -> query($query);
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/*
|
||
|
||
олучение одной записи из БД
|
||
|
||
$item = DB::getRow("SELECT * FROM `category` WHERE `id` = ?", 1);
|
||
|
||
// Или
|
||
|
||
$item = DB::getRow("SELECT * FROM `category` WHERE `id` = :id", array('id' => 1));
|
||
|
||
|
||
|
||
print_r($item);
|
||
|
||
PHP
|
||
Результат:
|
||
|
||
Array
|
||
|
||
(
|
||
|
||
[id] => 1
|
||
|
||
[parent] => 0
|
||
|
||
[name] => Мороженое
|
||
|
||
)
|
||
|
||
Получение нескольких записей из БД
|
||
|
||
$items = DB::getAll("SELECT * FROM `category` WHERE `id` > 2");
|
||
|
||
print_r($items);
|
||
|
||
PHP
|
||
Результат:
|
||
|
||
Array
|
||
|
||
(
|
||
|
||
[0] => Array
|
||
|
||
(
|
||
|
||
[id] => 3
|
||
|
||
[parent] => 0
|
||
|
||
[name] => Фрукты
|
||
|
||
)
|
||
|
||
[1] => Array
|
||
|
||
(
|
||
|
||
[id] => 4
|
||
|
||
[parent] => 0
|
||
|
||
[name] => Ягоды
|
||
|
||
)
|
||
|
||
[2] => Array
|
||
|
||
(
|
||
|
||
[id] => 5
|
||
|
||
[parent] => 2
|
||
|
||
[name] => Грибы
|
||
|
||
)
|
||
|
||
...
|
||
|
||
)
|
||
|
||
Получения значения
|
||
|
||
$value = DB::getValue("SELECT `name` FROM `category` WHERE `id` = 2");
|
||
|
||
print_r($value);
|
||
|
||
PHP
|
||
Результат:
|
||
|
||
Овощи
|
||
|
||
Получения значений колонки
|
||
|
||
$values = DB::getColumn("SELECT `name` FROM `category`");
|
||
|
||
print_r($values);
|
||
|
||
PHP
|
||
Результат:
|
||
|
||
Array
|
||
|
||
(
|
||
|
||
[0] => Мороженое
|
||
|
||
[1] => Овощи
|
||
|
||
[2] => Фрукты
|
||
|
||
[3] => Ягоды
|
||
|
||
[4] => Грибы
|
||
|
||
[5] => Морепродукты
|
||
|
||
...
|
||
|
||
)
|
||
|
||
Добавление в БД
|
||
|
||
Метод возвращает ID вставленной записи.
|
||
|
||
$insert_id = DB::add("INSERT INTO `category` SET `name` = ?", 'Яблоки');
|
||
|
||
PHP
|
||
Все остальные запросы
|
||
|
||
Выполняет запросы в БД, такие как DELETE, UPDATE, CREATE TABLE и т.д. В случаи успеха возвращает true.
|
||
|
||
DB::set("DELETE FROM `category` WHERE `id` > ? AND `parent` > ?", array(123, 0));
|
||
*/
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
?>
|