<?php
/*
Автор : Atkat && vShalamov
*/
class Db {
protected $db;
public function __construct() {
$cfg = [
'host' => 'localhost', ### Хост базы ###
'charset' => 'utf8', ### Кодировка ###
'name' => 'wm', ### База данных ###
'user' => 'wm', ### Пользователь ###
'password' => 'EZTlb@123',]; ### Пароль ###
try{
$this->db = new PDO('mysql:host='.$cfg['host'].';charset='.$cfg['charset'].';dbname='.$cfg['name'].'', $cfg['user'], $cfg['password'],[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true]);
} catch (PDOException $e) {
die('Нет соединения с БД! <br>Ошибка:<b> ' . $e->getMessage().'</b>'); }
}
// Пример кода - $db-query('DELETE FROM users WHERE id = :id',['id'=>1]);
public function query ($sql, $params = []) {
$stmt = $this->db->prepare($sql);
foreach ($params as $key => $val) {
$type = PDO::PARAM_INT;
} else {
$type = PDO::PARAM_STR;
}
$stmt->bindValue(':'.$key, $val, $type);
}
}
$stmt->execute();
return $stmt;
}
// Пример кода - $aray = $db-fetchAll('SELECT * FROM users WHERE name = :name and last = :last',['name'=>'name','last'=>'last']);
// Использовать для циклов
public function fetchAll ($sql, $params = []) {
$result = $this->query($sql, $params);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
// Пример кода - $array = $db-fetch('SELECT * FROM users WHERE name = :name and last = :last',['name'=>'name','last'=>'last']);
// Вывод на экран $array['параметр']
public function fetch ($sql, $params = []) {
$result = $this->query($sql, $params);
return $result->fetch();
}
// Пример кода - $array = $db-object('SELECT * FROM users WHERE name = :name and last = :last',['name'=>'name','last'=>'last']);
// Вывод на экран $array->параметр
public function object ($sql, $params = []) {
$result = $this->query($sql, $params);
return $result->fetch(PDO::FETCH_OBJ);
}
public function column ($sql, $params = []) {
$result = $this->query($sql, $params);
return $result->fetchColumn();
}
public function lastInsertId () {
return $this->db->lastInsertId();
}
// Пример кода - $db-fast_query('SELECT * FROM users WHERE name = ? and last = ?',['name','last']);
public function fast_query ($sql,$params = []) {
$result = $this->db->prepare($sql);
return $result->execute($params);
}
// Пример кода - $array = $db-fast_fetch('SELECT * FROM users WHERE name = ? and last = ?',['name','last']);
public function fast_fetch ($sql,$params = []) {
$result = $this->db->prepare($sql);
$result->execute($params);
return $result->fetch();
}
}
$db = new Db();