PHP Language How to exploit PHP abilities www
PHP Language How to exploit PHP abilities? www. supinfo. com Copyright © SUPINFO. All rights reserved
PHP Language Course objectives By completing this course, you will: n Understand the PHP syntax n Use the PHP abilities
PHP Language Course topics These are the parts that we will approach: n Basic syntax n Control Structures n Functions n Arrays
PHP Language Basic Syntax Understand the PHP code’s architecture
Basic syntax Preview These are the chapters that we will approach : n Markups and commentaries n Variables n Types n Operators
Basic syntax Markups and commentaries n PHP instructions are put between markups: n <? php … ? > n Other markups to proscribe: n <? … ? > n <% … %> n <script language="php">…</script> n Commentaries // just one line /* several lines */
Basic syntax Variables n Casse sensitive n Prefixed by a $ (dollar) n Authorized: n $_var; n $Var; n Forbidden: n $123 var;
Basic syntax Variables n Declaration $var = "value"; n Concatenation $var = $foo. $bar; $var = $foo. n Destruction unset($var); "word";
Basic syntax Types n Weak typing: n No need to declare variables n Automatic and implicit conversion n 8 different types: n 4 scalar types: string, int, float and boolean n 2 composed types: array, object n 2 special types: resource, NULL
Basic syntax Operators n Mathematics operators: n + - * / % ++ -n Comparison operators: n == === != n <> < > >= <= n Logical operators: n && ||
Basic syntax Stop-and-think Do you have any questions?
PHP Language Control structures
Control structures Preview These are the chapters that we will approach : n if … elseif. . . else n switch n while, do. . . while n foreach n break n continue
Control structures if … else n if requires a condition if ($str == "Hello") { // Code } n else enables to do execute code if the condition is false. if ($str == "Hello") { // Code } else { // Code }
Control structures if … else n Ternary operator (Equivalent to if … else) (condition) ? Instr if TRUE : Instr if FALSE n elseif enables to do several different tests. if ($str == "Hello") { // Code } elseif ($str == "Bye") { // Code } else { // Code }
Control structures switch n Similar to if … else switch ($str) { case "Hello": // Code break; n Tests’succession on the input variable’s value case "Bye": // Code break; default: n The code in default is executed if all tests fail // Code break; }
Control structures Loops n Loops while the condition is true while ($int < 10) { echo $int++; } n At least one execution… $int = 1; do { echo $int; } while ($int < 0);
Control structures Loops n For for ($i = 0 ; $i < 10 ; $i++) { echo $i; } n Foreach $array = array('apple', 'lemon', 'mangoe'); foreach ($array as $key => $value) { echo $key. " : ". $value; }
Control structures Special behavior n Break while ($int++ < 10) { break; } n Continue for ($i = 0 ; $i < 10 ; $i++) { if ($i == 1) continue; echo $i; }
Control structures Stop-and-think Do you have any questions?
PHP Language Functions
Functions Preview These are the chapters that we will approach : n Functions’ declaration n Functions’ use
Functions Declaration n Arguments can have default value. n Functions can yield results. function foo($arg 1, $arg 2 = "World") { return $arg 1. $arg 2; } echo foo("Hello"); // displays Hello. World echo foo("Viva", "PHP"); // displays Viva. PHP
Functions Global Keyword n Use of an external variable $i = 0; function foo() { global $i; $i += 10; } foo(); echo $i; // displays 10
Functions Passage by reference n The argument is not a value’s copy anymore, the value is directly modified in the memory. function foo(&$arg 1) { $arg 1 += 10; } $i = 10; foo($i); echo $i; // Displays 20
Functions Stop-and-think Do you have any questions?
PHP Language Arrays
Arrays Preview These are the chapters that we will approach : n Declaration n Use n Some functions on arrays
Arrays Use n Gets an element thanks to its index (or its key) $fruits = array('apple', 'lemon', 'mangoe'); echo $fruits[2]; // displays mangoe $fruits[2] = 'strawberry'; echo $fruits[2]; // displays strawberry
Arrays Utilisation n Function print_r(): Displays the array’s keys and values n Useful for debugging $fruits = array('apple', 'lemon', 'mangoe'); print_r($fruits); n Results: Array ( [0] => apple [1] => lemon [2] => mangoe )
Arrays Associative arrays n Explicit association key => value n The key is defined by the developer $promos = array( 'B 1' => 'Year 2013', 'B 2' => 'Year 2012', 'B 3' => 'Year 2011', 'M 1' => 'Year 2010', 'M 2' => 'Year 2009');
Arrays Functions : count() and sizeof() n Count the elements of the array count($fruits); // 3 n The sizeof() function is a count() alias. sizeof($fruits); // 3
Arrays Functions : explode() and implode() n explode() : Create an array from a string $array = explode(' ', 'Viva PHP'); echo $array[0]; // displays Viva n implode() : Creation a string from an array $str = implode(', ', $fruits); echo $str; // displays apple, lemon, mangoe
Arrays Stop-and-think Do you have any questions?
Interact with users in PHP Data’s appropriation. www. supinfo. com Copyright © SUPINFO. All rights reserved
Interact with users in PHP Course objectives By completing this course, you will be able to: n Handle data from an user. n Keep informations about an user. n Send an email.
Interact with users in PHP Preview These are the chapters that we will approach : n GET & POST methods n Predefined variables n Cookies n Sessions n Mail function
Interact with users in PHP GET & POST methods n Submitting data to the server. n 2 methods : n GET : data sent with the URL n Appear in the browser search. php? name=bibifoc&sort=DESC n POST : data sent in the HTTP header
Interact with users in PHP Predefined variables n Data received by the URL (GET) $_GET['name'] search. php? name=bibifoc&sort=DESC n Data received by the HTTP header (POST) $_POST['pass'] <input name="pass" type="password" /> n File received by forms: $_FILES['user_photo'] <input name="user_photo" type="file" />
Interact with users in PHP Cookies Warning : cookies must be sent before anything is outputted to the browser. n Creation : setcookie('cookie_name', $content, $time. Length); n 3 methods to acces: echo $my_cookie; echo $HTTP_COOKIE_VARS['my_cookie']; echo $_COOKIE['my_cookie']; n Destroying : setcookie('cookie_name', '', 1);
Interact with users in PHP Sessions n Creation : Session : session_start(); n Must be called before anything is outputted to the browser. . Variable : $_SESSION['us_name'] = $_POST['login']; n Destroying : n Variable : unset($_SESSION['us_name']); n Session : session_destroy();
Interact with users in PHP Mail function Template function : bool mail($dest, $subject, $message[, $headers]); Exemple : 1 <? php 2 3 4 5 6 7 8 9 10 11 12 13 14 ? > $dest = 'fabien. berger@supinfo. com'; $subject = 'Example'; $message = "Hey. n"; $message. = "How are you ? "; $headers = "From: thierry. boidart@supinfo. com rn"; $headers. = "Reply-to: benjamin. bouche@supinfo. com"; if(mail($dest, $subject, $message, $headers)) { echo "Mail send"; } else { echo "Failure Mail"; }
Sending mail Stop-and-think Do you have any questions ?
Advanced PHP Discover the main functions proposed by PHP www. supinfo. com Copyright © SUPINFO. All rights reserved
Advanced PHP Course topics These are the parts that we will approach : n Inclusion functions n Dates management n Buffering functions n String functions n Array functions n Manipulation of files
Advanced PHP Inclusion functions
Inclusion functions Preview These are the chapters that we will approach : n Utility of an inclusion function n Difference between include() and require() n Function include() and require()
Inclusion functions Utility of an inclusion function n Used to include a file in a script. n Two usable functions : include() and require(). n These two functions do not return the same type of error.
Inclusion functions Difference between include() and require() n The function include() will display a WARNING in case of error : the script is not stopped. Warning: include(my_file. php) [function. include]: failed to open stream: No such file or directory in /Websites/test. php on line 2 n The function require() will immediately stop the execution of the script in case of error.
Inclusion functions Stop-and-think Do you have any questions?
Advanced PHP Dates management
Dates management Preview These are the chapters that we will approach : n The UNIX timestamp n Function time() n Function date()
Dates management The UNIX timestamp UNIX Timestamp - System for describing points in time, defined as the number of seconds elapsed since the January 1, 1970, not counting leap seconds.
Dates management Function time() The function time() returns the current time measured with an UNIX timestamp. 1. 2. 3. 4. 5. 6. 7. <? php echo "Now : ". time(); // Now : 1216736314 echo "In a week : ". time() + (3600 * 24 * 7); // In a week : 1217341114 ? >
Dates management Function date() The function date() returns a string formatted according to the given format. 1. 2. 3. 4. <? php echo date("d/m/y H: i: s", 1216736314); // 22/07/08 16: 18: 34 ? > Without the second argument, the function date()returns the current date string formatted according to the given format.
Dates management Function date() Main characters recognized for the date format. d Day of the month, 2 digits with leading zeros m Numeric representation of a month, with leading zeros Y A full numeric representation of a year, 4 digits y A full numeric representation of a year, 2 digits H 24 -hour format of an hour with leading zeros h 12 -hour format of an hour with leading zeros i Minutes with leading zeros s Seconds with leading zeros
Dates management Stop-and-think Do you have any questions?
Advanced PHP Buffering functions
Buffering functions Preview These are the chapters that we will approach : n Concept of buffering n Function ob_start() n Function ob_end_clean() n Function ob_end_flush() n Function ob_flush()
Buffering functions Concept of buffering The buffering (or output control) functions allow you to control when output is sent from the script. It also avoids the error: headers already sent and is therefore very useful.
Buffering functions Function ob_start() The function ob_start() turns on output buffering. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. 1. 2. 3. 4. 5. 6. 7. 8. 9. . <? php function callback($buffer){ return (ereg_replace("a", "b", $buffer)); } ob_start("callback"); // Buffering with a callback function ob_start(); // Another buffering
Buffering functions Function ob_end_clean() The function ob_end_clean() discards the contents of the topmost output buffer and turns off this output buffering. 1. 2. 3. 4. 5. <? php ob_start(); echo "Text which will not be displayed"; ob_end_clean(); ? >
Buffering functions Function ob_clean() The function ob_clean() discards the contents of the output buffer. This function does not destroy the output buffer like ob_end_clean() does. 1. 2. 3. 4. 5. <? php ob_start(); echo "Text which will not be displayed"; ob_clean(); ? >
Buffering functions Function ob_end_flush() The function ob_end_flush() will send the contents of the topmost output buffer (if any) and turn this output buffer off. 1. 2. 3. 4. 5. 6. <? php ob_start(); echo "Welcome in SUPINFO"; ob_end_flush() ; // Welcome in SUPINFO ? >
Buffering functions Function ob_flush() The function ob_flush() will send the contents of the output buffer (if any). This function does not destroy the output buffer like ob_end_flush() does. 1. 2. 3. 4. 5. 6. <? php ob_start(); echo "Welcome in SUPINFO"; ob_flush(); // Welcome in SUPINFO ? >
Buffering functions Stop-and-think Do you have any questions?
Advanced PHP String functions
String functions Preview These are the chapters that we will approach : n Function strlen() n Function substr() n Function str_replace()
String functions Function strlen() The function strlen() returns the length or the argument. 1. 2. 3. 4. 5. 6. <? php $nombre = strlen("Welcome in SUPINFO"); echo "Characters : $nombre"; // Characters : 18 ? >
String functions Function substr() The function substr() returns the portion of a string specified by the second and the third arguments. 1. 2. 3. 4. 5. 6. 7. 8. <? php echo substr("SUPINFO", 0, 3); // SUP echo substr("SUPINFO", -1); // O echo substr("SUPINFO", -4, 2); // IN ? > Warning : contrary to the second, the third argument of this function corresponds to a number of characters to be recovered, not a position.
String functions Function str_replace() The function str_replace() can replace an occurrence by another in a string. 1. 2. 3. 4. 5. 6. 7. 8. <? php $string = "I bought tomatoes"; $research= "tomatoes"; $replace= "pineapples"; echo str_replace($research, $replace, $string); // I bought pineapples ? >
String functions Stop-and-think Do you have any questions?
Advanced PHP Array functions
Array functions Preview These are the chapters that we will approach : n Function array_push() n Function array_unshift() n Function array_pop() n Function array_shift() n Function sort()
Array functions Function array_push() The function array_push() treats an array as a stack, and pushes the passed variables at its end. 1. 2. 3. 4. 5. <? php $array = array("chair", "table"); array_push($array, "stool", "bench"); print_r($array); ? > Array ( [0] [1] [2] [3] ) => => chair table stool bench
Array functions Function array_unshift() The function array_unshift() adds passed elements in the front of the array. 1. 2. 3. 4. 5. <? php $array = array("chair", "table"); array_unshift($array, "bench"); print_r($array); ? > Array ( [0] => bench [1] => chair [2] => table )
Array functions Function array_pop() The function array_pop() pops and returns the last value of the array, shortening it by one element. 1. 2. 3. 4. 5. <? php $array = array("chair", "table", "bench"); array_pop($array); print_r($array); ? > Array ( [0] => chair [1] => table )
Array functions Function array_shift() The function array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. 1. 2. 3. 4. 5. <? php $array = array("chair", "table", "bench"); array_shift($array); print_r($array); ? > Array ( [0] => table [1] => bench )
Array functions Function sort() The function sort() sorts an array. Elements will be arranged from lowest to highest when this function has completed. 1. 2. 3. 4. 5. <? php $array = array("chair", "table", "bench"); sort($array); print_r($array); ? > Array ( [0] => bench [1] => chair [2] => table )
Array functions Stop-and-think Do you have any questions?
Advanced PHP Manipulation of files
Manipulation of files Preview These are the chapters that we will approach : n Opening a file n Simplified reading n Simplified writing n Copy of a file n Deleting a file
Manipulation of files Opening a file The function fopen() binds a named resource specified by the argument, to a stream. 1. 2. 3. 4. 5. <? php $file = fopen("file. txt", "r"); . . . fclose($file); ? > The function fclose()will close the file pointed by the argument.
Manipulation of files Opening a file The different ways to open a file. r Reading only, pointer at the beginning r+ Reading an writing, pointer at the beginning w Writing only, deleting the content, pointer at the beginning w+ Reading and writing, deleting the content, pointer at the beginning a a+ Writing only, pointer at the end Reading and writing, pointer at the end x Create and open for writing only, pointer at the beginning x+ Create and open for reading and writing, pointer at the begenning
Manipulation of files Simplified reading The function file_get_contents() reads the entire file and returns it as a string. 1. 2. 3. 4. <? php $content = file_get_contents("file. txt"); echo $content; ? >
Manipulation of files Simplified writing The function file_put_contents() opens a file, puts content inside and closes it. 1. 2. 3. 4. 5. 6. <? php file_put_contents("file. txt", include("file. txt"); // Welcome in SUPINFO ? > "Welcome in SUPINFO");
Manipulation of files Copy of a file The function copy() makes a copy of a file. 1. 2. 3. 4. 5. 6. 7. 8. <? php $file = "file. txt"; $copy = "file_copy. txt"; if(copy($file, $copy)){ echo "The file has been copied"; } ? >
Manipulation of files Deleting a file The function unlink() deletes a file. 1. 2. 3. 4. 5. 6. 7. <? php $file = "file. txt"; if(unlink($file)){ echo "The file has been deleted"; } ? >
Manipulation of files Stop-and-think Do you have any questions?
OOP and PHP Object-Oriented Programming with PHP www. supinfo. com Copyright © SUPINFO. All rights reserved
OOP and PHP Course objectives By completing this course, you will: n Be introduced to the concept of OOP with PHP. n Learn creation of object and class syntax. n Know some keywords and advanced methods for OOP with PHP. n Approach how to control exceptions.
OOP and PHP Course topics Course’s plan : n Basics. n Exceptions controls
OOP and PHP Basics At the beginning of OOP
Basics Course topics Course’s plan : n OOP in real world. n Basic syntax n Constructors and Destructors n Member visibility n Static keywords
Basics OOP in real world n OOP Terms : n Class: – vehicle; n Objects: – car; n Methods: – Move; n Properties: – Color.
Basics Basic syntax Class definition: Class declaration Attribute definition Methods definition 1. class My. Class 2. { 3. 4. private $var = "Hello "; 5. 6. 7. public function Hello( $s_name ) 8. { 9. echo $this->var. " ". $s_name. "!"; 10. } 11. 12. }
Basics Basic syntax Instantiation method: Call default constructor using the keyword « new » 1. $instance = new My. Class(); 2. 3. $instance->Hello( "World" ); 4. // Displays Hello World! Call Hello() method of My. Class class
Basics Basic syntax Inheritance method: n Class: Definition of base class. Define derived class who extends base class 1. class My. Class 2. { 3. protected $var = "Hello World!"; 4. } 5. 6. class Other. Class extends My. Class 7. { 8. public function Hello() 9. { 10. echo $this->var; 11. } 12. }
Basics Basic syntax Inheritance concept: n Instantiation. Call extended class constructor 1. $instance = new Other. Class(); 2. 3. $instance->Hello(); 4. // Displays Hello, World! Displays variable value of parent class
Basics Constructors and Destructors Class defined with one property Class constructor defined with one parameter Class destructor defined 1. class My. Class 2. { 3. private $var; 4. 5. public function __construct( $string = "" ) 6. { 7. $this->var = $string; 8. } 9. 10. public function __destruct() 11. { 12. // … 13. } 14. }
Basics Member visibility n public: n Reachable from everywhere. n protected: n Reachable from the class itself and its extended classes. n private: n restricts the access to the class itself.
Basics Static keyword n Enables to access to methods or class variables without instantiating this class. n Static members : 1. class Foo 2. { 3. public static $my_static = 'foo'; 4. public function static. Value() { 5. return self: : $my_static; 6. } 7. } 8. 9. echo Foo: : $my_static; // Displays Foo 10. 11. $instance = new Foo(); 12. echo $instance->static. Value(); // Displays Foo
Basics Stop-and-think Do you have any questions?
OOP and PHP Exceptions controls
Exceptions controls Course topics Course’s plan : n Some functions n Error managment
Exceptions controls Some functions Exception n Some useful methods of this class: n get. Message() § Returns the message in paramater of constructor § Returns an error message n get. Line() § Returns the number of error’s line. n get. File() § Returns file name where error occured. n get. Code() § Returns exception code
Exceptions controls Error management Exception class use 1. 2. 3. 5. 6. 7. 8. 9. 10. 11. 12. try { if((1+1)!=1) { throw new Exception ('one plus one isn't equal to one'); } } catch (Exception $e) { print " Exception n°: ". $e->get. Code(); print " Message : ". $e->get. Message(); print " File : ". $e->get. File(); print " Lign : ". $e->get. Line(); } throw keyword raises an exception. try catch block allows to catch exceptions raised by the script and apply proper treatment.
Exceptions controls Stop-and-think Do you have any questions?
PHP and databases How to interact with databases in PHP Campus-Booster ID : 51461
PHP and databases Course objectives By completing this course, you will: n Learn about My. SQL n Be able to interact with databases using PHP
PHP and databases Course topics Course’s plan: n Presentation of My. SQL n Using mysql_ functions n Using PDO extension
My. SQL Presentation
My. SQL Preview These are the chapters that we will approach: n Presentation. n Discovering PHPMy. Admin
My. SQL Presentation When the ele. PHPant meets the dolphin! n Most popular open source SQL databases server. n RDBMS most often used with PHP. n Management inferface : PHPMy. Admin n Fast, reliable, robust and multi-platform n Secure n Access controls, privileges, etc.
My. SQL PHPMy. Admin g n i r e Discov n i m d A y M P PH
My. SQL Stop-and-think Do you have any questions?
My. SQL functions How to connect to a My. SQL database in PHP 4 and 5
My. SQL functions Preview These are the chapters that we will approach: n Connecting to the database n Executing requests
My. SQL functions Managing connections n Connection to My. SQL Server 1. 2. $c = mysql_connect('localhost', 'John', 'Passw 0 rd'); mysql_select_db('World. Corp', $c); n Connecting to localhost server with username and password. n Selecting database for connection $c. n Second argument of mysql_select_db optional n By default : last connection initialized.
My. SQL functions Managing connections Disconnecting 1. 2. 3. 4. 5. 6. $c = mysql_connect('localhost', 'John', 'Passw 0 rd'); mysql_select_db('World. Corp', $c); // Data retrieving mysql_close($c); n Close database connection n Second argument of mysql_select_db optional n By default : last connection initialized. n Automatically executed at the script’s end
My. SQL functions Executing requests Function mysql_query() n Executes a query. 1. $sql = 'SELECT id, first. Name, last. Name FROM members'; 2. $req = mysql_query($sql, $c); n Returns: n If query order: ressource variable. n If inserting/editing order: boolean. n False if invalid order. n Second argument of mysql_select_db optional n By default : last connection initialized.
My. SQL functions Executing requests Function mysql_fetch_array() n Reads a data resource 1. 2. 3. 4. 5. 6. 7. $sql = 'SELECT id, first. Name, last. Name FROM members'; $req = mysql_query($sql, $c); while( $res = mysql_fetch_array($req, MYSQL_NUM) ) { echo '<p>'. $res[0]. '-'. $res[1]. ' '. $res[2]. '</p>'; } n Second argument: predefined constant n MYSQL_NUM : returns digital array. n MYSQL_ASSOC : returns associative array. n MYSQL_BOTH (by default) : returns both arrays.
My. SQL functions Executing requests Function mysql_num_rows() n Returns the count of results in a resource. 1. 2. 3. 4. 5. 6. 7. 8. $sql = 'SELECT id, first. Name, last. Name FROM members'; $req = mysql_query($sql, $c); if(mysql_num_rows($req) == 0) echo "No member found. "; else { // Displaying members’ list }
My. SQL functions Executing requests Function mysql_result() n Returns a resource’s content 1. $sql = 'SELECT COUNT(*) FROM members'; 2. $req = mysql_query($sql, $c); 3. echo mysql_result($req, 0). ' members found. '; n Not very efficient. n Use it only for a restricted number of data. n Prefer to use mysql_fetch_array function. n Arguments: 1. Data resource 2. Line number (optional) 3. Field number (optional)
My. SQL functions Free ressources Function mysql_free_result() n Frees memory used by a resource. 1. 2. 3. 4. 5. 6. $sql = 'SELECT * FROM members'; $req = mysql_query($sql, $c); // Data processing mysql_free_result($req); n Useful if huge data process. n May deteriorate light requests.
My. SQL functions Stop-and-think Do you have any questions?
PDO PHP 5 extension, PHP 6 standard
PDO Preview These are the chapters that we will approach: n Presentation and advantages. n How to use it?
PDO Presentation P HP Data Object
PDO Advantages n Abstraction of database server nature n Object oriented aspect (different from mysql_ functions) n Using exceptions n PHP 6 standard, PHP 5 extension
PDO My. SQL connection string 1. 2. 3. 4. 5. 6. $connection. String = "mysql: dbname=World. Corp; "; $connection. String. = "host=127. 0. 0. 1; "; $connection. User = "John"; $connection. Password = "Passw 0 rd"; $c = new PDO($connection. String, $connection. User, $connection. Password); n My. SQL does not allow to give username and password directly in connection string.
PDO Oracle connection string 1. 2. 3. 4. 5. 6. $connection. String = "oci: dbname=//localhost: 1521/"; $connection. String. = "World. Corp"; $connection. User = "John"; $connection. Password = "Passw 0 rd"; $c = new PDO($connection. String, $connection. User, $connection. Password); n Oracle does not allow to give username and password directly in connection string.
PDO DB 2 connection string 1. 2. 3. 4. 5. 6. $connection. String = "odbc: DRIVER={IBM DB 2 ODBC DRIVER}; "; $connection. String. = "HOSTNAME=localhost; PORT=50000; "; $connection. String. = "DATABASE=World. Corp; PROTOCOL=TCPIP; "; $connection. String. = "UID=John; PWD=Passw 0 rd; "; $c = new PDO($connection. String, ''); n DB 2 accepts username and password in connection string.
PDO Attributes n Throwing exceptions instead of warnings: $c->set. Attribute(PDO: : ATTR_ERRMODE , PDO: : ERRMODE_EXCEPTION); n More oriented object n Buffering SQL queries : $c->set. Attribute(PDO: : MYSQL_ATTR_USE_BUFFERED_QUERY, true) n My. SQL attribute n Increases general My. SQL performances
PDO Connection with exceptions 1. $connection. String = "mysql: dbname=World. Corp; "; 2. $connection. String. = "host=127. 0. 0. 1; "; 3. $connection. User = "John"; 4. $connection. Password = "Passw 0 rd"; 5. 6. try 7. { 8. $c = new PDO($connection. String, $connection. User, $connection. Password); 9. } 10. catch( Exception $e ) 11. { 12. echo "Error occured : ". $e->get. Message(); 13. Log: : Write. Error($e->get. Message); 14. } n Line 13: other log class, to keep an history of all errors.
PDO Executing a query n Two kinds of requests: n Classical queries: § Queries similar to mysql_ functions. n Prepared queries: § More efficient. § More secure (prevent from SQL injections). § Return statement object.
PDO Syntax n Classical request: $sql = 'SELECT id FROM members WHERE first. Name = '. $first. Name; n Possibility of SQL injection, if $first. Name is not checked. n Control depending on database server. n Prepared request: $sql = 'SELECT id FROM members WHERE first. Name = ? '; n Variables replaced by ? . n Avoid SQL injections risks. n Escaping independant from database server. n Quotes automatically inserted by PDO.
PDO Preparation n Using of prepare method. 1. $c = new PDO($connection. String, $connection. User, $connection. Password); 2. 3. $sql = 'SELECT id FROM members WHERE first. Name = ? '; 4. 5. $select = $c->prepare($sql); 6. 7. $sql = 'UPDATE members 8. SET 9. first. Name = "John" 10. WHERE 11. first. Name = "Paul"'; 12. 13. $update = $c->prepare($sql); n Returns a statement object.
PDO Executing a request n Using execute method $sql = 'SELECT id FROM members WHERE first. Name = ? '; $select = $c->prepare($sql); $select->execute(array($_POST['first. Name‘])); $sql = ‘UPDATE members SET first. Name = 'John' WHERE first. Name = "Paul"'; $update = $c->prepare($sql); $count = $update->execute(); n Argument: array of values, replacing placeholders. n Returns: n Inserting/edition order: number of affected rows. n SELECT order: nothing.
PDO Read SELECT results n Method fetch. All 1. $sql = 'SELECT id, first. Name FROM members WHERE first. Name = ? '; 2. $select = $c->prepare($sql); 3. $select->execute(array($_POST[‘first. Name‘])); 4. $datas = $select->fetch. All(PDO: : FETCH_NUM); 5. 6. echo '<pre>'; print_r($datas); echo '</pre>'; /* Displays: Array( [0] => 1, [1] => "John" ) ) */
PDO Fetch Styles n Argument of fetch. All : the Fetch Style. n Modify the structure of returned results. n Examples : n PDO: : FETCH_ASSOC: associatives arrays n PDO: : FETCH_NUM: digital arrays; n PDO: : FETCH_BOTH : by default. Both above. n PDO: : FETCH_OBJ : objects. n PDO: : FETCH_CLASS : instances of class. n If using PDO: : FETCH_CLASS, mapping between class attributes and database fields.
PDO Fetch Styles P Using S S A L C _ H C T E DO: : F
PDO Place holders n Two kinds of place holders. n Anonymous (? ) n Named (: nom) n Anonymous place holders to avoid, if a lot of variables. n For instance : $sql = 'SELECT id, first. Name FROM members WHERE id = : id'; n Place holders for LIMIT are not allowed before My. SQL 5. 07.
PDO Method bind. Param() n Maps a place holder with a value. n Possibility to specify a variable type. n Anonymous place holder: $sql = 'SELECT id, first. Name FROM members WHERE id = ? '; $select = $c->prepare($sql); $select->bind. Param(0, $id, PDO: : PARAM_INT); n Named place holder: $sql = 'SELECT id, first. Name FROM members WHERE id = : id'; $select = $c->prepare($sql); $select->bind. Param(': id', $id, PDO: : PARAM_INT);
PDO Place holders n Specify expected values n PDO: : PARAM_STR n PDO: : PARAM_INT n PDO: : PARAM_NULL n PDO: : PARAM_LOB n PDO: : PARAM_BOOL n If PDO: : PARAM_STR, possibility to specify the maximum length of the string.
PDO Disconnecting n Destroying PDO object unset($c); n That’s all Folks!
PDO Stop-and-think Do you have any questions?
Congratulations You have successfully completed the SUPINFO refresher course : PHP
PHP The end n Practice is the best way to learn n Enjoy PHP 6 Soon …
- Slides: 149