|
PHP - Подключение к базе данных (PDO)
PHP - Подключение к базе данных (PDO)
PDO (PHP Data Objects) - расширение для PHP, предоставляющее разработчику универсальный интерфейс для доступа к различным базам данных
Чтобы проверить какие БД поддерживает
1 2 3 4 5
|
<?php echo "<pre>"; print_r(PDO::getAvailableDrivers()); echo "</pre>"; ?>
|
1 2 3
|
<?php $link = new PDO("mssql:host=$host;dbname=$dbname", $user, $pass,$options); ?>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
<?php
Class DB { private $link; public function __construct(){ try{ $this->connect(); } catch(PDOException $e){ throw new Exception($e->getMessage()); } } private function connect(){ $config = require_once($_SERVER['DOCUMENT_ROOT'].'/class/db_config.php'); $dsn = "mysql:host=".$config['host'].";dbname=".$config['db'].";charset=".$config['charset']; $this->link = new PDO($dsn, $config['user'], $config['pass']); $this->link->exec('SET NAMES utf8'); return $this; } public function execute($sql) { // prepare подготавливает запрос к выполнению $sth = $this->link->prepare($sql); return $sth->execute(); } public function query($sql) { // prepare подготавливает запрос к выполнению $sth = $this->link->prepare($sql); $sth->execute(); $res = $sth->fetchAll(PDO::FETCH_ASSOC); if($res === false) { return array(); } return $res; } public function lastInsertId() { $sth = $this->link->lastInsertId(); return $sth; }
}
$db = new DB();
?>
|
Ссылки по теме:
- progi.pro
- Соединение PHP PDO Class
|