Download presentation
Presentation is loading. Please wait.
Published byJonah Henderson Modified over 9 years ago
1
РНР. Уровень 4. Проектирование и разработка сложных веб-проектов на РНР 5 PHP Data Objects
2
Темы модуля Введение PDO - PHP Data Objects Лабораторная работа
3
PDO – PHP Data Objects DBLIB: FreeTDS / Microsoft SQL Server / Sybase Firebird (http://firebird.sourceforge.net/): Firebird/Interbase 6http://firebird.sourceforge.net/ IBM (IBM DB2) INFORMIX - IBM Informix Dynamic Server MYSQL (http://www.mysql.com/): MySQL 3.x/5.xhttp://www.mysql.com/ OCI (http://www.oracle.com): Oracle Call Interface ODBC: ODBC v3 (IBM DB2 and unixODBC) PGSQL (http://www.postgresql.org/): PostgreSQLhttp://www.postgresql.org/ SQLITE (http://sqlite.org/): SQLite 2.x/3.xhttp://sqlite.org/ PDO::getAvailableDrivers()
4
Соединение с БД MySQL mysql_connect($host, $user, $password); mysql_select_db($db); SQLite $dbh = sqlite_open($db, 0666); PostgreSQL pg_connect("host=$host dbname=$db user=$user password=$password"); MySQL $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass); SQLite $conn = new PDO("sqlite:$db"); PostgreSQL $conn = new PDO("pgsql:host=$host dbname=$db", $user, $pass);
5
Строки соединения с различными БД MySQL ("mysql:host=hostname;dbname=mysql", "username", "password") SQLite ("sqlite:/path/to/database.db") ("sqlite::memory:") PostgreSQL ("pgsql:dbname=pdo;host=hostname", "username", "password" ) Oracle ("OCI:dbname=mydatabase;charset=UTF-8", "username", "password") ODBC ("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\database.mdb;Uid=Admin") Firebird ("firebird:dbname=hostname:C:\path\to\database.fdb", "username", "password") Informix ("informix:DSN=InformixDB", "username", "password") DBLIB ("dblib:host=hostname:port;dbname=mydb","username","password")
6
Использование файла конфигурации Файл config.ini db.conn="mysql:host=localhost;dbname=test" db.user=“vasya" db.pass=“parol“ Загрузка файла конфигурации $params = parse_ini_file("config.ini"); Соединение с БД $conn = new PDO($params['db.conn'], $params['db.user'], $params['db.pass']);
7
Выполнение запроса к БД $sql = ‘INSERT INTO users VALUES(‘john’, ‘john@smith.com’); MySQL mysql_connect('localhost', 'vasya', 'parol'); mysql_select_db('users'); $result = mysql_query($sql); SQLite $dbh = sqlite_open('/path/to/users.db'); $result = sqlite_query($sql, $dbh); PostgreSQL pg_connect("host=localhost dbname=users user=vasya password=parol"); $result = pg_query($sql); PDO $conn = new PDO($conn, $user, $password); $result = $conn->exec($sql);
8
Выборка данных из БД $sql = 'SELECT name FROM users ORDER BY name'; MySQL mysql_connect('localhost', 'vasya', 'parol'); mysql_select_db('users'); $result = mysql_query($sql); SQLite $dbh = sqlite_open('/path/to/users.db'); $result = sqlite_query($sql, $dbh); PostgreSQL pg_connect("host=localhost dbname=users user=vasya password=parol"); $result = pg_query($sql); PDO $conn = new PDO($conn, $user, $password); $result = $conn->query($sql);
9
Фильтрация строк SELECT * FROM users WHERE name='$name' $name = $_POST['name']; MySQL $name = mysql_real_escape_string($name); SQLite $name = sqlite_escape_string($name); PostgreSQL $name = pg_escape_string($name); PDO $name = $conn->quote($name); $result = $conn->query("SELECT * FROM users WHERE name='$name'");
10
Режимы FETCH MySQL $result = mysql_query($sql); $row = mysql_fetch_assoc($result); $row = mysql_fetch_array($result, MYSQL_ASSOC); SQLite $result = sqlite_query($dbh, $sql); $row = sqlite_fetch_array($result, SQLITE_ASSOC); PostgreSQL $result = pg_query($sql); $row = pg_fetch_assoc($result); $row = pg_fetch_assoc($result, 0, PGSQL_ASSOC); PDO $stmt = $conn->query($sql); $result = $stmt->fetch(PDO::FETCH_ASSOC); $result = $stmt->fetch(PDO::FETCH_NUM); $result = $stmt->fetch(PDO::FETCH_BOTH);
11
Режимы FETCH (продолжение) FETCH OBJECT $obj = $stmt->fetch(PDO::FETCH_OBJ); echo $obj->id.' '; echo $obj->name.' '; echo $obj->email; FETCH LAZY $result = $stmt->fetch(PDO::FETCH_LAZY); echo $result[0].' '; echo $result['name'].' '; echo $result->email;
12
Работа с классами class User{ public $id; public $name; public $email; function showInfo(){ echo ' '.$this->name.' : '.$this->email.' '; } } $obj = $stmt->fetchALL(PDO::FETCH_CLASS, 'User'); foreach($obj as $user) $user->showInfo(); $users = $stmt->fetchObject('User'); $user = new User(); $stmt = $dbh->query($sql); $stmt->setFetchMode(PDO::FETCH_INTO, $user);
13
Обработка ошибок $dbh = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password); Exception $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Warning $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); Silent $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); Info echo $dbh->errorCode(); print_r($dbh->errorInfo());
14
Использование подготовленных запросов $stmt = $dbh->prepare("SELECT * FROM users WHERE id = :id AND name = :name"); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->execute(); $stmt = $dbh->prepare("SELECT * FROM users WHERE id = ? AND name = ?"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->bindParam(2, $name, PDO::PARAM_STR); $stmt->execute(); $data = array('id'=>1, 'name'=>'Ivan'); $stmt = $dbh->prepare("SELECT * FROM users WHERE id = :id AND name = :name"); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->execute($data);
15
Связывание полей таблицы $sql = 'SELECT id, name, email FROM users'; $stmt = $dbh->prepare($sql); $stmt->execute(); $stmt->bindColumn(1, $id); $stmt->bindColumn(2, $name); $stmt->bindColumn('email', $email); while ($row = $stmt->fetch(PDO::FETCH_BOUND)) { $data = $id. "\t". $name. "\t". $email. "\n"; print $data; }
16
Транзакции $users = file(USERS_FILE); try { $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction(); foreach($users as $user){ list($name, $email) = explode("|", $user); $dbh->exec("INSERT INTO users (name, email) VALUES ($name, $email)"); } $dbh->commit(); }catch(PDOException $e){ $dbh->rollback(); }
17
PDO и шаблон «Одиночка» class DB{ private static $instance = NULL; private function __construct(){} private function __clone(){} public static function getInstance(){ if(!self::$instance){ self::$instance = new PDO('sqlite2:users.db'); self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return self::$instance; } try{ $result = DB::getInstance()->query("SELECT * FROM users"); }catch(PDOException $e){ echo $e->getMessage(); }
18
Лабораторная работа Файл pdo\pdo-spl-1.php 1 1 Выполните задания 1-5 2 2 Выполните задание 6-7 3 3 Использование PDO и SPL Выполните задание 8-10 4 4
19
Выводы PDO - PHP Data Objects Соединение с БД Выполнение запроса к БД Фильтрация строк Режимы FETCH Работа с классами Обработка ошибок Использование подготовленных запросов Использование транзакций
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.