Download presentation
1
PDO, PHP Data Object Use a Database with PHP www.supinfo.com
21-Apr-17 [Title of the course] PDO, PHP Data Object Use a Database with PHP Copyright © SUPINFO. All rights reserved Copyright © NameOfTheOrganization. All rights reserved.
2
Course objectives At the end of this lesson you will be able to:
21-Apr-17 PDO, PHP Data Object [Title of the course] Course objectives At the end of this lesson you will be able to: Explain what is PDO. Use PDO in a PHP project. Manage Transactions with PDO. Explain and use Prepared Statements. Copyright © NameOfTheOrganization. All rights reserved.
3
Course topics Course plan: Introduction. Basics.
21-Apr-17 PDO, PHP Data Object [Title of the course] Course topics Course plan: Introduction. Basics. Transaction Management. Prepared Statements. Copyright © NameOfTheOrganization. All rights reserved.
4
[Title of the course] Why PDO ?
21-Apr-17 [Title of the course] PDO, PHP Data Object Introduction Why PDO ? Copyright © NameOfTheOrganization. All rights reserved.
5
Preview Here the chapters which we will approach: Before PDO…
21-Apr-17 Introduction [Title of the course] Preview Here the chapters which we will approach: Before PDO… … and now. PDO Architecture. Advantages. Installation. Copyright © NameOfTheOrganization. All rights reserved.
6
Before PDO… PDO is only available since PHP 5.
21-Apr-17 Introduction [Title of the course] Before PDO… PDO is only available since PHP 5. In PHP 4, you must use one of native extension dedicated to database access : mysqli for MySQL. oci8 for Oracle. … Each extension provides different specific functions. Need to change the code if you want to change the DBMS ! Not a good approach… Copyright © NameOfTheOrganization. All rights reserved.
7
…and now. PDO is the main new feature of PHP 5.1.
21-Apr-17 Introduction [Title of the course] …and now. PDO is the main new feature of PHP 5.1. Object Oriented extension : Provides ease of use and greater abstraction. A common base for all the DBMS connectors : No more need to change the code when you want to change of DBMS. Or almost… Copyright © NameOfTheOrganization. All rights reserved.
8
PDO Architecture Introduction PHP >= 5.1 PDO PDO MySQL PDO Oracle
21-Apr-17 Introduction [Title of the course] PDO Architecture PHP >= 5.1 PDO PDO MySQL PDO Oracle MySQL PDO SQL Server PDO … Copyright © NameOfTheOrganization. All rights reserved.
9
Advantages PDO is written in C language :
21-Apr-17 Introduction [Title of the course] Advantages PDO is written in C language : Similar performance as the old native drivers. Optimization opportunities thanks to prepared statements. Not available with the old MySQL extension. PDO can execute all query types : INSERT, UPDATE, DELETE, SELECT Stored procedure. Copyright © NameOfTheOrganization. All rights reserved.
10
21-Apr-17 Introduction [Title of the course] Installation PDO and all the major drivers ship with PHP as shared extensions. You simply need to activate them by editing the php.ini file : If you use a PHP version < 5.3 : Add or uncomment the following line : For all PHP version : extension=php_pdo.so ;(ou .dll sous Windows) extension=php_pdo_mysql.so ;(ou .dll) Copyright © NameOfTheOrganization. All rights reserved.
11
Do you have any questions ?
21-Apr-17 Introduction [Title of the course] Stop-and-think Do you have any questions ? Copyright © NameOfTheOrganization. All rights reserved.
12
[Title of the course] Connection to a Database, execute a query, …
21-Apr-17 [Title of the course] PDO, PHP Data Object Basics Connection to a Database, execute a query, … Copyright © NameOfTheOrganization. All rights reserved.
13
Preview Here the chapters which we will approach: PDO Classes.
21-Apr-17 Basics [Title of the course] Preview Here the chapters which we will approach: PDO Classes. PDO Example. Database connection. Perform a query. Retrieve results. Fetch Styles. Copyright © NameOfTheOrganization. All rights reserved.
14
PDO Classes The three main PDO classes that we’ll used are :
21-Apr-17 Basics [Title of the course] PDO Classes The three main PDO classes that we’ll used are : PDO : the link to the Database. PDOStatement : represent a statement and its results. PDOException : the exception thrown when an error occurs. Copyright © NameOfTheOrganization. All rights reserved.
15
PDO Example $user = 'root'; $password = 'root';
21-Apr-17 Basics [Title of the course] PDO Example $user = 'root'; $password = 'root'; $dsn = 'mysql:host=localhost;dbname=example'; try { $pdo = new PDO($dsn, $user, $password); } catch (PDOException $e) { die("Error ! : ".$e->getMessage()); } $pdo->exec("INSERT INTO sample (col) VALUES ('val')"); $result = $pdo->query("SELECT col FROM sample"); while($row = $result->fetch()) { print_r($row); $pdo = NULL; Copyright © NameOfTheOrganization. All rights reserved.
16
21-Apr-17 Basics [Title of the course] Database connection The first thing to do is to create a PDO class instance. The constructor take three parameters : The DSN (Database Source Name) : The information about the Database to use. Example for a MySQL Database : The Username to use to connect to the Database. The Password of the account. Create a PDO instance can throw an exception : If the necessary driver is not loaded. If the access is denied. … mysql:host=localhost;port=3306;dbname=example Copyright © NameOfTheOrganization. All rights reserved.
17
21-Apr-17 Basics [Title of the course] Database connection To use several Database, just create several PDO instance : $user1 = 'root'; $password1 = 'root'; $dsn1 = 'mysql:host=localhost;dbname=example1'; try { $pdo1 = new PDO($dsn1, $user1, $password1); } catch (PDOException $e) { die(); } $user2 = 'root'; $password2 = 'root'; $dsn2 = 'mysql:host=localhost;dbname=example2'; $pdo2 = new PDO($dsn2, $user2, $password2); Copyright © NameOfTheOrganization. All rights reserved.
18
21-Apr-17 Basics [Title of the course] Perform a query Once your connection is open, you can execute query thanks to two methods of PDO instance : int exec ( string $statement ) : Executes an SQL statement in a single function call, returning the number of rows affected by the statement. PDOStatement query ( string $statement ) : Executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object. Copyright © NameOfTheOrganization. All rights reserved.
19
Perform a query Basics SQL Statement PDO method INSERT exec() UPDATE
21-Apr-17 Basics [Title of the course] Perform a query SQL Statement PDO method INSERT exec() UPDATE DELETE SELECT query() EXPLAIN SHOW DESC Copyright © NameOfTheOrganization. All rights reserved.
20
21-Apr-17 Basics [Title of the course] Retrieve results After a call to the method query() retrieved data are kept in memory, inside a PDOStatement instance. The two main methods to manipulate this data are : array fetchAll( [ $fetch_style=PDO::FETCH_BOTH] ) Returns an array containing all of the result set rows. mixed fetch( [$fetch_style=PDO::FETCH_BOTH] ) Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row. Copyright © NameOfTheOrganization. All rights reserved.
21
21-Apr-17 Basics [Title of the course] Retrieve results The fetchAll() method returns all the data in an array. Very easy to use ! But not advisable if query return a large number of result ! In that case, fetch() method is the best choice ! Copyright © NameOfTheOrganization. All rights reserved.
22
Retrieve results Fetch all example : Sequential fetch example :
21-Apr-17 Basics [Title of the course] Retrieve results Fetch all example : Sequential fetch example : $sql = "SELECT login, password FROM users"; $sth = $pdo->query($sql); $result = $sth->fetchAll(PDO::FETCH_ASSOC); foreach($result as $row) { echo $row['login'].'-'.$row['password'].'<br/>'; } $sql = "SELECT login, password FROM users"; $sth = $pdo->query($sql); while($row = $sth->fetch(PDO::FETCH_ASSOC)) { echo $row['login'].'-'.$row['password'].'<br/>'; } Copyright © NameOfTheOrganization. All rights reserved.
23
Fetch Styles Basics VALUE ACTION PDO::FETCH_ASSOC
21-Apr-17 Basics [Title of the course] Fetch Styles VALUE ACTION PDO::FETCH_ASSOC Returns an array indexed by column name as returned in your result set. PDO::FETCH_NUM Returns an array indexed by column number as returned in your result set, starting at column 0. PDO::FETCH_BOTH Returns an array indexed by both column name and 0-indexed column number as returned in your result set. PDO::FETCH_OBJ Returns an anonymous object with property names that correspond to the column names returned in your result set. PDO::FETCH_CLASS Returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. Copyright © NameOfTheOrganization. All rights reserved.
24
Fetch Styles PDO::FETCH_ASSOC :
21-Apr-17 Basics [Title of the course] Fetch Styles PDO::FETCH_ASSOC : $sql = "SELECT login, password FROM users"; $sth = $pdo->query($sql); $result = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($result); Array ( [0] => Array [login] => Plop [password] => 1234 ) Copyright © NameOfTheOrganization. All rights reserved.
25
Fetch Styles PDO::FETCH_BOTH :
21-Apr-17 Basics [Title of the course] Fetch Styles PDO::FETCH_BOTH : $sql = "SELECT login, password FROM users"; $sth = $pdo->query($sql); $result = $sth->fetchAll(PDO::FETCH_BOTH); print_r($result); Array ( [0] => Array [login] => Plop [0] => Plop [password] => 1234 [1] => Plop ) Copyright © NameOfTheOrganization. All rights reserved.
26
Fetch Styles PDO::FETCH_OBJ :
21-Apr-17 Basics [Title of the course] Fetch Styles PDO::FETCH_OBJ : $sql = "SELECT login, password FROM users"; $sth = $pdo->query($sql); $result = $sth->fetchAll(PDO::FETCH_OBJ); print_r($result); Array ( [0] => stdClass Object [login] => Plop [password] => 1234 ) Copyright © NameOfTheOrganization. All rights reserved.
27
21-Apr-17 Basics [Title of the course] Last Insert ID When you insert a new row inside a table, you often let the DBMS generate the primary key. You can retrieve the last generated ID thanks to the instance method of PDO : string lastInsertId ([ string $name = NULL ]) : If a sequence name was not specified for the name parameter, returns a string representing the row ID of the last inserted row. Else, returns a string representing the last value retrieved from the specified sequence object. $sql = "INSERT INTO users (login, password) VALUES ('john.doe', 'Plop')”; $pdo->exec($sql); echo $pdo->lastInsertId(); // Display the last generated ID Copyright © NameOfTheOrganization. All rights reserved.
28
Do you have any questions ?
21-Apr-17 Basics [Title of the course] Stop-and-think Do you have any questions ? Copyright © NameOfTheOrganization. All rights reserved.
29
Exercises Now, you know how to use Database in PHP !
Basics Content Starter Set Exercises Now, you know how to use Database in PHP ! Create two new classes : PdoUserManager implements UserManager interface. PdoPostManager implements PostManager interface. Implement methods using PDO and a MySQL Database. Update your PHP page to use your new managers instead of the old ones. They are no register method for now, so add an user directly in Database with a MySQL browser like phpMyAdmin.
30
Transaction Management
21-Apr-17 [Title of the course] PDO, PHP Data Object Transaction Management Commit, Rollback & cie. Copyright © NameOfTheOrganization. All rights reserved.
31
Preview Here the chapters which we will approach: Presentation.
21-Apr-17 Transaction Management [Title of the course] Preview Here the chapters which we will approach: Presentation. Case Study. Provided methods. Example. Copyright © NameOfTheOrganization. All rights reserved.
32
21-Apr-17 Transaction Management [Title of the course] Presentation Transaction is useful when you want defined a unified set of queries. If they all succeed, changes are applied. If one fails, no changes are applied. We name commit the operation that applied changes in Database. Copyright © NameOfTheOrganization. All rights reserved.
33
21-Apr-17 Transaction Management [Title of the course] Case study For instance, transactions are very important in banking applications : Imagine a bank transfer. The operation is in two steps : Withdraw money of one account. Add it to an other. Imagine each step is a Database query. What happen if the second query failed ? Where is the money ? Copyright © NameOfTheOrganization. All rights reserved.
34
21-Apr-17 Transaction Management [Title of the course] Provided methods PDO instances provide three methods to manage transactions : bool beginTransaction ( void ) : Turns off auto-commit mode and so, changes made to the database via the PDO object instance are not committed until you end the transaction. bool commit ( void ) : Commits a transaction, returning the database connection to auto-commit mode. bool rollBack ( void ) : Rolls back the current transaction, returning the database connection to auto-commit mode. Copyright © NameOfTheOrganization. All rights reserved.
35
Example // Define to PDO to generate errors as exceptions
21-Apr-17 Transaction Management [Title of the course] Example // Define to PDO to generate errors as exceptions $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->beginTransaction(); try { $sql1 = "INSERT INTO author (firstname, lastname) VALUES ( 'Clark', 'Kent' )"; $pdo->exec($sql); $sql2 ="INSERT INTO article(title, body, author_id) VALUES('Plop', '...',".$pdo->lastInsertId().")"; $pdo->exec($sql2); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); echo ”Error: ".$e->getMessage(); } Copyright © NameOfTheOrganization. All rights reserved.
36
Do you have any questions ?
21-Apr-17 Transaction Management [Title of the course] Stop-and-think Do you have any questions ? Copyright © NameOfTheOrganization. All rights reserved.
37
[Title of the course] Improved your queries.
21-Apr-17 [Title of the course] PDO, PHP Data Object Prepared Statement Improved your queries. Copyright © NameOfTheOrganization. All rights reserved.
38
Preview Here the chapters which we will approach: Presentation.
21-Apr-17 Prepared Statement [Title of the course] Preview Here the chapters which we will approach: Presentation. Execution Cycle. Parameterized Prepared Statements. Provided methods. Example. Copyright © NameOfTheOrganization. All rights reserved.
39
21-Apr-17 Prepared Statement [Title of the course] Presentation Many of the more mature databases support the concept of prepared statements. A prepared query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. The database will analyze, compile and optimize it's plan for executing them. Avoid repeating the analyze/compile/optimize cycle. Protects against SQL injection. This means that prepared statements use fewer resources, run faster and are more secure ! Copyright © NameOfTheOrganization. All rights reserved.
40
Execution Cycle Prepared Statement Classic Statement or Analyze
21-Apr-17 Prepared Statement [Title of the course] Execution Cycle Classic Statement or first execution cycle of a prepared statement. Analyze Compile Next execution cycle for a prepared statement. Optimize Run Copyright © NameOfTheOrganization. All rights reserved.
41
Parameterized Prepared Statements
21-Apr-17 Prepared Statement [Title of the course] Parameterized Prepared Statements A parameterized prepared statement is a prepared statement that you can define parameters. Two types of parameterized prepared statements : With ordered parameters : With named parameters : You can’t make a prepared statement mixing the two types of parameters. $sql = "INSERT INTO users (login, password) VALUES (?, ?)”; $sql = "INSERT INTO users (login, password) VALUES (:login, :password)”; Copyright © NameOfTheOrganization. All rights reserved.
42
21-Apr-17 Prepared Statement [Title of the course] Provided methods Once your statement is ready, you need to provide it to your DBMS. To do that, you must use the following instance method of PDO class : PDOStatement prepare ( string $statement ). $sql = "INSERT INTO users (login, password) VALUES (?, ?)”; $statement = $pdo->prepare($sql); Copyright © NameOfTheOrganization. All rights reserved.
43
Provided methods Once your statement is prepare, you can use it !
21-Apr-17 Prepared Statement [Title of the course] Provided methods Once your statement is prepare, you can use it ! To define the statement parameters, you have two ways : Passing them in parameters of the execute() instance method of PDOStatement. Use the bindValue() instance method of PDOStatement. Copyright © NameOfTheOrganization. All rights reserved.
44
Example Example passing parameters to execute() :
21-Apr-17 Prepared Statement [Title of the course] Example Example passing parameters to execute() : $sql = "INSERT INTO author (firstname, lastname) VALUES ( :firstname, :lastname )"; $statement = $pdo->prepare($sql); $firstname = 'John'; $lastname = 'Doe'; $statement->execute( array(':firstname' => $firstname, ':lastname' => $lastname ) ); Copyright © NameOfTheOrganization. All rights reserved.
45
Example Example using bindValue() :
21-Apr-17 Prepared Statement [Title of the course] Example Example using bindValue() : $sql = "INSERT INTO author (firstname, lastname) VALUES ( :firstname, :lastname )"; $statement = $pdo->prepare($sql); $firstname = 'John'; $lastname = 'Doe'; $statement->bindValue(':firstname', $firstname); $statement->bindValue(':lastname', $lastname); $statement->execute(); Copyright © NameOfTheOrganization. All rights reserved.
46
Do you have any questions ?
21-Apr-17 Prepared Statement [Title of the course] Stop-and-think Do you have any questions ? Copyright © NameOfTheOrganization. All rights reserved.
47
Prepared Statements Content Starter Set Exercises (1/5) The code to create a new PDO instance inside your both managers are the same… Maybe you have defined your Database information inside each of them ? Very bad ! Imagine you want to change your Database ? You should update each manager… Remember : D(on’t) R(epeat) Y(ourself) !
48
Exercises (2/5) Create a new abstract class named AbstractPdoManager:
Prepared Statements Content Starter Set Exercises (2/5) Create a new abstract class named AbstractPdoManager: Define each of your connection parameters as a constant inside it. Define a constructor that use this parameters to create a PDO instance. Keep it into a protected instance variable. Update your managers to extends this class and use his instance variable. After that, you’ll DRY !
49
Prepared Statements Content Starter Set Exercises (3/5) Now you now that Prepared Statements are more secure and more efficient. Update your managers to use Prepared Statements.
50
Exercises (4/5) Create the new domain class Comment :
Prepared Statements Content Starter Set Exercises (4/5) Create the new domain class Comment : With attributes : id : an unique identifier. body : the content of the comment. post : the post where the comment has been posted. user : the author of the comment if authenticated when the comment was posted. publicationDate : the publication date of the comment. With just getters and setters as instance methods.
51
Exercises (5/5) Update the Post class :
Prepared Statements Content Starter Set Exercises (5/5) Update the Post class : Add a new attributes named comments. It represents the comments of the post. Add a getter and a setter for that attribute. Update the PdoPostManager to return Posts with their comments. Create a new interface named CommentManager and an implementation named PdoCommentManager with : addComment($body, $post, $user) method. Update the display post page : Add a form to post a comment. Display the comments linked to the current post inside the display post page.
52
Summary of the Module PDO advantages DBMS Query Prepared Statements
21-Apr-17 PDO, PHP Data Object [Title of the course] Summary of the Module PDO advantages DBMS Query Prepared Statements Transactions Copyright © NameOfTheOrganization. All rights reserved.
53
Available on Cyberlibris.
21-Apr-17 PDO, PHP Data Object [Title of the course] For more If you want to go into these subjects more deeply, … Publications PHP 5 avancé 5e édition. Éric DASPET Cyril PIERRE DE GEYER Available on Cyberlibris. Web sites Copyright © NameOfTheOrganization. All rights reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.