• Aucun résultat trouvé

PHP Language if … elseif … else – Cours et formation gratuit

N/A
N/A
Protected

Academic year: 2022

Partager "PHP Language if … elseif … else – Cours et formation gratuit"

Copied!
149
0
0

Texte intégral

(1)

How to exploit PHP abilities?

www.supinfo.com

Copyright © SUPINFO. All rights reserved

(2)

Course objectives

Understand the PHP syntax

Use the PHP abilities

By completing this course, you will:

(3)

Course topics

Basic syntax

Control Structures

Functions

Arrays

These are the parts that we will approach:

(4)

Basic Syntax

Understand the PHP code’s architecture

(5)

Preview

 Markups and commentaries

 Variables

 Types

 Operators

These are the chapters that we will approach :

(6)

 PHP instructions are put between markups:

<?php … ?>

 Other markups to proscribe:

<? … ?>

<% … %>

<script language="php">…</script>

Markups and commentaries

 Commentaries

// just one line /* several

lines */

(7)

 Casse sensitive

 Prefixed by a $ (dollar)

 Authorized:

$_var;

$var;

$Var;

 Forbidden:

$123var;

Variables

(8)

 Declaration

 Concatenation

 Destruction

Variables

$var = "value";

$var = $foo . $bar;

$var = $foo . "word";

unset($var);

(9)

 Weak typing:

 No need to declare variables

 Automatic and implicit conversion

 8 different types:

 4 scalar types: string, int, float and boolean

 2 composed types: array, object

 2 special types: resource, NULL

Types

(10)

 Mathematics operators:

 + - * / % ++ --

 Comparison operators:

 == === !=

 <> < <= > >=

 Logical operators:

 && ||

Operators

(11)

Stop-and-think

Do you have any questions?

(12)

Control structures

(13)

Preview

 if … elseif ... else

 switch

 while, do ... while

 for

 foreach

 break

 continue

These are the chapters that we will approach :

(14)

if … elseif … else

if requires a condition

else enables to do execute code if the condition is false.

if ($str == "Hello") { // Code

}

if ($str == "Hello") { // Code

} else {

// Code }

(15)

if … elseif … else

 Ternary operator (Equivalent to ifelse)

elseif enables to do several different tests.

if ($str == "Hello") { // Code

} elseif ($str == "Bye") { // Code

} else {

// Code }

(condition) ? Instr if TRUE : Instr if FALSE

(16)

 Similar to ifelseifelse

 Tests’succession on the input variable’s value

 The code in default is executed if all tests fail

switch ($str) { case "Hello":

// Code break;

case "Bye":

// Code break;

default:

// Code break;

}

switch

(17)

 Loops while the condition is true

 At least one execution…

while ($int < 10) { echo $int++;

}

Loops

$int = 1;

do {

echo $int;

} while ($int < 0);

(18)

 For

 Foreach

for ($i = 0 ; $i < 10 ; $i++) {

echo $i;

}

Loops

$array = array('apple', 'lemon', 'mangoe');

foreach ($array as $key => $value) {

echo $key . " : " . $value;

}

(19)

 Break

 Continue

while ($int++ < 10) { break;

}

Special behavior

for ($i = 0 ; $i < 10 ; $i++) {

if ($i == 1) continue;

echo $i;

}

(20)

Stop-and-think

Do you have any questions?

(21)

Functions

(22)

Preview

 Functions’ declaration

 Functions’ use

These are the chapters that we will approach :

(23)

 Arguments can have default value.

 Functions can yield results.

function foo($arg1, $arg2 = "World") {

return $arg1 . $arg2;

}

echo foo("Hello"); // displays HelloWorld

echo foo("Viva", "PHP"); // displays VivaPHP

Declaration

(24)

 Use of an external variable

$i = 0;

function foo() {

global $i;

$i += 10;

}

foo();

echo $i; // displays 10

Global Keyword

(25)

 The argument is not a value’s copy anymore, the value is directly modified in the memory.

function foo(&$arg1) {

$arg1 += 10;

}

$i = 10;

foo($i);

echo $i; // Displays 20

Passage by reference

(26)

Stop-and-think

Do you have any questions?

(27)

Arrays

(28)

Preview

 Declaration

 Use

 Some functions on arrays

These are the chapters that we will approach :

(29)

 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

Use

(30)

 Function print_r(): Displays the array’s keys and values

 Useful for debugging

 Results:

$fruits = array('apple', 'lemon', 'mangoe');

print_r($fruits);

Utilisation

Array ( [0] => apple [1] => lemon [2] =>

mangoe )

(31)

 Explicit association key => value

 The key is defined by the developer

$promos = array(

'B1' => 'Year 2013', 'B2' => 'Year 2012', 'B3' => 'Year 2011', 'M1' => 'Year 2010', 'M2' => 'Year 2009');

Associative arrays

(32)

 Count the elements of the array

 The sizeof() function is a count() alias.

Functions : count() and sizeof()

sizeof($fruits); // 3 count($fruits); // 3

(33)

explode() : Create an array from a string

implode() : Creation a string from an array

$array = explode(' ', 'Viva PHP');

echo $array[0]; // displays Viva

Functions : explode() and implode()

$str = implode(', ', $fruits);

echo $str; // displays apple, lemon, mangoe

(34)

Stop-and-think

Do you have any questions?

(35)

www.supinfo.com

Copyright © SUPINFO. All rights reserved

Data’s appropriation.

(36)

Handle data from an user.

Keep informations about an user.

Send an email.

By completing this course, you will be able to:

Course objectives

(37)

Preview

 GET & POST methods

 Predefined variables

 Cookies

 Sessions

 Mail function

These are the chapters that we will approach :

(38)

GET & POST methods

 Submitting data to the server.

 2 methods :

 GET : data sent with the URL

 Appear in the browser

 POST : data sent in the HTTP header search.php?name=bibifoc&sort=DESC

(39)

Predefined variables

$_GET['name']

$_POST['pass']

$_FILES['user_photo']

search.php?name=bibifoc&sort=DESC

<input name="pass" type="password" />

<input name="user_photo" type="file" />

 Predefined variables

 Data received by the URL (GET)

 Data received by the HTTP header (POST)

 File received by forms:

(40)

Cookies

Warning : cookies must be sent

before anything is outputted to the browser

.

 Creation :

 3 methods to acces:

 Destroying :

setcookie('cookie_name', $content, $timeLength);

echo $my_cookie;

echo $HTTP_COOKIE_VARS['my_cookie'];

echo $_COOKIE['my_cookie'];

setcookie('cookie_name', '', 1);

(41)

Sessions

 Creation : Session :

 Must be called before anything is outputted to the browser.

.

Variable :

 Destroying :

 Variable :

 Session :

session_start();

session_destroy();

$_SESSION['us_name'] = $_POST['login'];

unset($_SESSION['us_name']);

(42)

Mail function

bool mail($dest, $subject, $message[, $headers]);

<?php

$dest = '[email protected]';

$subject = 'Example';

$message = "Hey.\n";

$message .= "How are you ?";

$headers = "From: [email protected] \r\n";

$headers .= "Reply-to: [email protected]";

if(mail($dest, $subject, $message, $headers)) { echo "Mail send";

} else {

echo "Failure Mail";

}

?>

1 2 3 4 5 6 7 8 9 10 11 12 13 14

Template function :

Exemple :

(43)

Stop-and-think

Do you have any questions ?

(44)

Discover the main functions proposed by PHP

www.supinfo.com

Copyright © SUPINFO. All rights reserved

(45)

Course topics

Inclusion functions

Dates management

Buffering functions

String functions

Array functions

Manipulation of files These are the parts that we will approach :

(46)

Inclusion functions

(47)

Preview

 Utility of an inclusion function

 Difference between include() and require()

 Function include() and require()

These are the chapters that we will approach :

(48)

Utility of an inclusion function

 Used to include a file in a script.

 Two usable functions : include() and require().

 These two functions do not return the same type of error.

(49)

Difference between include() and require()

 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

 The function require() will immediately stop the execution of the script in case of error.

(50)

Stop-and-think

Do you have any questions?

(51)

Dates management

(52)

Preview

 The UNIX timestamp

 Function time()

 Function date()

These are the chapters that we will approach :

(53)

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.

(54)

Function time()

The function time() returns the current time measured with an UNIX timestamp.

1. <?php

2. echo "Now : " . time();

3. // Now : 1216736314 4.

5. echo "In a week : " . time() + (3600 * 24 * 7);

6. // In a week : 1217341114 7. ?>

(55)

Function date()

The function date() returns a string formatted according to the given format.

1. <?php

2. echo date("d/m/y H:i:s",1216736314);

3. // 22/07/08 16:18:34 4. ?>

Without the second argument, the function date()returns the current date string formatted according to the given format.

(56)

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

(57)

Stop-and-think

Do you have any questions?

(58)

Buffering functions

(59)

Preview

 Concept of buffering

 Function ob_start()

 Function ob_end_clean()

 Function ob_clean()

 Function ob_end_flush()

 Function ob_flush()

These are the chapters that we will approach :

(60)

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.

(61)

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. <?php

2. function callback($buffer){

3. return (ereg_replace("a","b",$buffer));

4. } 5.

6. ob_start("callback");

7. // Buffering with a callback function 8. ob_start();

9. // Another buffering ...

(62)

Function ob_end_clean()

The function ob_end_clean() discards the contents of the topmost output buffer and turns off this output buffering.

1. <?php

2. ob_start();

3. echo "Text which will not be displayed";

4. ob_end_clean();

5. ?>

(63)

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. <?php

2. ob_start();

3. echo "Text which will not be displayed";

4. ob_clean();

5. ?>

(64)

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. <?php

2. ob_start();

3. echo "Welcome in SUPINFO";

4. ob_end_flush() ;

5. // Welcome in SUPINFO 6. ?>

(65)

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. <?php

2. ob_start();

3. echo "Welcome in SUPINFO";

4. ob_flush();

5. // Welcome in SUPINFO 6. ?>

(66)

Stop-and-think

Do you have any questions?

(67)

String functions

(68)

Preview

 Function strlen()

 Function substr()

 Function str_replace()

These are the chapters that we will approach :

(69)

Function strlen()

The function strlen() returns the length or the argument.

1. <?php

2. $nombre = strlen("Welcome in SUPINFO");

3.

4. echo "Characters : $nombre";

5. // Characters : 18 6. ?>

(70)

Function substr()

The function substr() returns the portion of a string specified by the second and the third arguments.

1. <?php

2. echo substr("SUPINFO",0,3);

3. // SUP

4. echo substr("SUPINFO",-1);

5. // O

6. echo substr("SUPINFO",-4,2);

7. // IN 8. ?>

Warning : contrary to the second, the third argument of this function corresponds to a number of characters to be

recovered, not a position.

(71)

Function str_replace()

The function str_replace() can replace an occurrence by another in a string.

1. <?php

2. $string = "I bought tomatoes";

3. $research= "tomatoes";

4. $replace= "pineapples";

5.

6. echo str_replace($research,$replace,$string);

7. // I bought pineapples 8. ?>

(72)

Stop-and-think

Do you have any questions?

(73)

Array functions

(74)

Preview

 Function array_push()

 Function array_unshift()

 Function array_pop()

 Function array_shift()

 Function sort()

These are the chapters that we will approach :

(75)

Function array_push()

The function array_push() treats an array as a stack, and pushes the passed variables at its end.

1. <?php

2. $array = array("chair","table");

3. array_push($array,"stool","bench");

4. print_r($array);

5. ?>

Array (

[0] => chair [1] => table [2] => stool [3] => bench )

(76)

Function array_unshift()

The function array_unshift() adds passed elements in the front of the array.

1. <?php

2. $array = array("chair","table");

3. array_unshift($array,"bench");

4. print_r($array);

5. ?>

Array (

[0] => bench [1] => chair [2] => table )

(77)

Function array_pop()

The function array_pop() pops and returns the last value of the array, shortening it by one element.

1. <?php

2. $array = array("chair","table","bench");

3. array_pop($array);

4. print_r($array);

5. ?>

Array (

[0] => chair [1] => table )

(78)

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. <?php

2. $array = array("chair","table","bench");

3. array_shift($array);

4. print_r($array);

5. ?>

Array (

[0] => table [1] => bench )

(79)

Function sort()

The function sort() sorts an array. Elements will be arranged from lowest to highest when this function has completed.

1. <?php

2. $array = array("chair","table","bench");

3. sort($array);

4. print_r($array);

5. ?>

Array (

[0] => bench [1] => chair [2] => table )

(80)

Stop-and-think

Do you have any questions?

(81)

Manipulation of files

(82)

Preview

 Opening a file

 Simplified reading

 Simplified writing

 Copy of a file

 Deleting a file

These are the chapters that we will approach :

(83)

Opening a file

The function fopen() binds a named resource specified by the argument, to a stream.

1. <?php

2. $file = fopen("file.txt","r");

3. ...

4. fclose($file);

5. ?>

The function fclose()will close the file pointed by the argument.

(84)

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 Writing only, pointer at the end

a+ 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

(85)

Simplified reading

The function file_get_contents() reads the entire file and returns it as a string.

1. <?php

2. $content = file_get_contents("file.txt");

3. echo $content;

4. ?>

(86)

Simplified writing

The function file_put_contents() opens a file, puts content inside and closes it.

1. <?php

2. file_put_contents("file.txt", "Welcome in SUPINFO");

3.

4. include("file.txt");

5. // Welcome in SUPINFO 6. ?>

(87)

Copy of a file

The function copy() makes a copy of a file.

1. <?php

2. $file = "file.txt";

3. $copy = "file_copy.txt";

4.

5. if(copy($file,$copy)){

6. echo "The file has been copied";

7. } 8. ?>

(88)

Deleting a file

The function unlink() deletes a file.

1. <?php

2. $file = "file.txt";

3.

4. if(unlink($file)){

5. echo "The file has been deleted";

6. } 7. ?>

(89)

Stop-and-think

Do you have any questions?

(90)

Object-Oriented Programming with PHP

www.supinfo.com

Copyright © SUPINFO. All rights reserved

(91)

Course objectives

Be introduced to the concept of OOP with PHP.

Learn creation of object and class syntax.

Know some keywords and advanced methods for OOP with PHP.

Approach how to control exceptions.

By completing this course, you will:

(92)

Course topics

Basics.

Exceptions controls

Course’s plan :

(93)

Basics

At the beginning of OOP

(94)

Course topics

 OOP in real world.

 Basic syntax

 Constructors and Destructors

 Member visibility

 Static keywords Course’s plan :

(95)

OOP in real world

 OOP Terms :

 Class:

– vehicle;

 Objects:

– car;

 Methods:

– Move;

 Properties:

– Color.

(96)

Basic syntax

1. class MyClass 2. {

3.

4. private $var = "Hello ";

5.

6.

7. public function Hello( $s_name ) 8. {

9. echo $this->var . " " . $s_name . "!";

10. } 11.

12. }

Class definition:

Class declaration

Attribute definition

Methods definition

(97)

Basic syntax

1. $instance = new MyClass();

2.

3. $instance->Hello( "World" );

4. // Displays Hello World!

Instantiation method:

Call default constructor using the keyword

« new »

Call Hello() method of MyClass class

(98)

Basic syntax

 Class:

1. class MyClass 2. {

3. protected $var = "Hello World!";

4. } 5.

6. class OtherClass extends MyClass 7. {

8. public function Hello() 9. {

10. echo $this->var;

11. } 12. }

Inheritance method:

Definition of base class.

Define derived class who extends base class

(99)

Basic syntax

 Instantiation.

Inheritance concept:

1. $instance = new OtherClass();

2.

3. $instance->Hello();

4. // Displays Hello, World!

Call extended class constructor

Displays variable value of parent class

(100)

Constructors and Destructors

1. class MyClass 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. } Class destructor

defined Class defined with

one property

Class constructor defined with one parameter

(101)

Member visibility

 public:

 Reachable from everywhere.

 protected:

 Reachable from the class itself and its extended classes.

 private:

 restricts the access to the class itself

.

(102)

Static keyword

 Enables to access to methods or class variables without instantiating this class.

 Static members :

1. class Foo 2. {

3. public static $my_static = 'foo';

4. public function staticValue() { 5. return self::$my_static;

6. } 7. } 8.

9. echo Foo::$my_static; // Displays Foo 10.

11. $instance = new Foo();

12. echo $instance->staticValue(); // Displays Foo

(103)

Stop-and-think

Do you have any questions?

(104)

Exceptions controls

(105)

Course topics

Some functions

Error managment Course’s plan :

(106)

Some functions

Some useful methods of this class:

getMessage()

Returns the message in paramater of constructor

Returns an error message

getLine()

Returns the number of error’s line.

getFile()

Returns file name where error occured.

getCode()

Returns exception code

Exception

(107)

throw keyword raises an exception.

try catch block allows to catch exceptions raised by the script and apply proper treatment.

Exception class use

Error management

1. try {

2. if((1+1)!=1) {

3. throw new Exception ('one plus one isn\'t equal to one');

5. } 6. }

7. catch (Exception $e) {

8. print "<br>Exception n°: ". $e->getCode();

9. print "<br>Message : ". $e->getMessage();

10. print "<br>File : ". $e->getFile();

11. print "<br>Lign : ". $e->getLine();

12. }

(108)

Stop-and-think

Do you have any questions?

(109)

How to interact with databases in PHP

Campus-Booster ID : 51461

(110)

Course objectives

Learn about MySQL

Be able to interact with databases using PHP

By completing this course, you will:

(111)

Course topics

 Presentation of MySQL

 Using mysql_ functions

 Using PDO extension Course’s plan:

(112)

Presentation

(113)

Preview

 Presentation.

 Discovering PHPMyAdmin

These are the chapters that we will approach:

(114)

Presentation

 Most popular open source SQL databases server.

 RDBMS most often used with PHP.

 Management inferface : PHPMyAdmin

 Fast, reliable, robust and multi-platform

 Secure

 Access controls, privileges, etc.

When the elePHPant meets the dolphin!

(115)

PHPMyAdmin

Discoverin g

PHPMyAd min

(116)

Stop-and-think

Do you have any questions?

(117)

How to connect to a MySQL database in PHP 4 and 5

(118)

Preview

 Connecting to the database

 Executing requests

These are the chapters that we will approach:

(119)

Managing connections

 Connection to MySQL Server

 Connecting to localhost server with username and password.

 Selecting database for connection $c.

 Second argument of mysql_select_db optional

 By default : last connection initialized.

1. $c = mysql_connect('localhost', 'John', 'Passw0rd');

2. mysql_select_db('WorldCorp', $c);

(120)

Managing connections

 Close database connection

 Second argument of mysql_select_db optional

 By default : last connection initialized.

 Automatically executed at the script’s end Disconnecting

1. $c = mysql_connect('localhost', 'John', 'Passw0rd');

2. mysql_select_db('WorldCorp', $c);

3.

4. // Data retrieving 5.

6. mysql_close($c);

(121)

Executing requests

 Executes a query.

 Returns:

 If query order: ressource variable.

 If inserting/editing order: boolean.

False if invalid order.

 Second argument of mysql_select_db optional

 By default : last connection initialized.

Function mysql_query()

1. $sql = 'SELECT id, firstName, lastName FROM members';

2. $req = mysql_query($sql, $c);

(122)

Executing requests

 Reads a data resource

 Second argument: predefined constant

 MYSQL_NUM : returns digital array.

 MYSQL_ASSOC : returns associative array.

 MYSQL_BOTH (by default) : returns both arrays.

Function mysql_fetch_array()

1. $sql = 'SELECT id, firstName, lastName FROM members';

2. $req = mysql_query($sql, $c);

3.

4. while( $res = mysql_fetch_array($req, MYSQL_NUM) ) 5. {

6. echo '<p>'.$res[0].'-'.$res[1].' '.$res[2]. '</p>';

7. }

(123)

Executing requests

 Returns the count of results in a resource.

Function mysql_num_rows()

1. $sql = 'SELECT id, firstName, lastName FROM members';

2. $req = mysql_query($sql, $c);

3.

4. if(mysql_num_rows($req) == 0) echo "No member found.";

5. else 6. {

7. // Displaying members’ list 8. }

(124)

Executing requests

Returns a resource’s content

Not very efficient.

Use it only for a restricted number of data.

Prefer to use mysql_fetch_array function.

Arguments:

1. Data resource

2. Line number (optional) 3. Field number (optional) Function mysql_result()

1. $sql = 'SELECT COUNT(*) FROM members';

2. $req = mysql_query($sql, $c);

3. echo mysql_result($req, 0).' members found.';

(125)

Free ressources

 Frees memory used by a resource.

 Useful if huge data process.

 May deteriorate light requests.

Function mysql_free_result()

1. $sql = 'SELECT * FROM members';

2. $req = mysql_query($sql, $c);

3.

4. // Data processing 5.

6. mysql_free_result($req);

(126)

Stop-and-think

Do you have any questions?

(127)

PHP 5 extension, PHP 6 standard

(128)

Preview

 Presentation and advantages.

 How to use it?

These are the chapters that we will approach:

(129)

P HP D ata

O bject

Presentation

(130)

Advantages

 Abstraction of database server nature

 Object oriented aspect (different from mysql_ functions)

 Using exceptions

 PHP 6 standard, PHP 5 extension

(131)

MySQL connection string

 MySQL does not allow to give username and password directly in connection string.

1. $connectionString = "mysql:dbname=WorldCorp;";

2. $connectionString .= "host=127.0.0.1;";

3. $connectionUser = "John";

4. $connectionPassword = "Passw0rd";

5.

6. $c = new PDO($connectionString, $connectionUser, $connectionPassword);

(132)

Oracle connection string

 Oracle does not allow to give username and password directly in connection string.

1. $connectionString = "oci:dbname=//localhost:1521/";

2. $connectionString .= "WorldCorp";

3. $connectionUser = "John";

4. $connectionPassword = "Passw0rd";

5.

6. $c = new PDO($connectionString, $connectionUser, $connectionPassword);

(133)

DB2 connection string

 DB2 accepts username and password in connection string.

1. $connectionString = "odbc:DRIVER={IBM DB2 ODBC DRIVER};";

2. $connectionString .= "HOSTNAME=localhost;PORT=50000;";

3. $connectionString .= "DATABASE=WorldCorp;PROTOCOL=TCPIP;";

4. $connectionString .= "UID=John;PWD=Passw0rd;";

5.

6. $c = new PDO($connectionString, '' , '');

(134)

Attributes

 Throwing exceptions instead of warnings:

 More oriented object

 Buffering SQL queries :

 MySQL attribute

 Increases general MySQL performances

$c->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);

$c->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)

(135)

Connection with exceptions

Line 13: other log class, to keep an history of all errors.

1. $connectionString = "mysql:dbname=WorldCorp;";

2. $connectionString .= "host=127.0.0.1;";

3. $connectionUser = "John";

4. $connectionPassword = "Passw0rd";

5.

6. try 7. {

8. $c = new PDO($connectionString, $connectionUser, $connectionPassword);

9. }

10. catch( Exception $e ) 11. {

12. echo "Error occured : ".$e->getMessage();

13. Log::WriteError($e->getMessage);

14. }

(136)

Executing a query

 Two kinds of requests:

 Classical queries:

 Queries similar to mysql_ functions.

 Prepared queries:

 More efficient.

 More secure (prevent from SQL injections).

 Return statement object.

(137)

Syntax

 Classical request:

 Possibility of SQL injection, if $firstName is not checked.

 Control depending on database server.

 Prepared request:

 Variables replaced by ?.

 Avoid SQL injections risks.

 Escaping independant from database server.

 Quotes automatically inserted by PDO.

$sql = 'SELECT id FROM members WHERE firstName = ?';

$sql = 'SELECT id FROM members WHERE firstName = '.$firstName;

(138)

Preparation

 Using of prepare method.

 Returns a statement object.

1. $c = new PDO($connectionString, $connectionUser, $connectionPassword);

2.

3. $sql = 'SELECT id FROM members WHERE firstName = ?';

4.

5. $select = $c->prepare($sql);

6.

7. $sql = 'UPDATE members

8. SET

9. firstName = "John"

10. WHERE

11. firstName = "Paul"';

12.

13. $update = $c->prepare($sql);

(139)

Executing a request

 Using execute method

 Argument: array of values, replacing placeholders.

 Returns:

 Inserting/edition order: number of affected rows.

SELECT order: nothing.

$sql = 'SELECT id FROM members WHERE firstName = ? ';

$select = $c->prepare($sql);

$select->execute(array($_POST['firstName‘]));

$sql = ‘UPDATE members SET firstName = 'John' WHERE firstName = "Paul"';

$update = $c->prepare($sql);

$count = $update->execute();

(140)

Read SELECT results

 Method fetchAll

1. $sql = 'SELECT id, firstName FROM members WHERE firstName = ?';

2. $select = $c->prepare($sql);

3. $select->execute(array($_POST[‘firstName‘]));

4. $datas = $select->fetchAll(PDO::FETCH_NUM);

5.

6. echo '<pre>'; print_r($datas); echo '</pre>';

/* Displays:

Array(

[0] => Array(

[0] => 1, [1] => "John"

) ) */

(141)

Fetch Styles

 Argument of fetchAll : the Fetch Style.

 Modify the structure of returned results.

 Examples :

 PDO::FETCH_ASSOC: associatives arrays

 PDO::FETCH_NUM: digital arrays;

 PDO::FETCH_BOTH : by default. Both above.

 PDO::FETCH_OBJ : objects.

 PDO::FETCH_CLASS : instances of class.

 If using PDO::FETCH_CLASS, mapping between class attributes and database fields.

(142)

Fetch Styles

Using

PDO::FET CH_CLAS S

(143)

Place holders

 Two kinds of place holders.

 Anonymous (?)

 Named (:nom)

 Anonymous place holders to avoid, if a lot of variables.

 For instance :

 Place holders for LIMIT are not allowed before MySQL 5.07.

$sql = 'SELECT id, firstName FROM members WHERE id = :id';

(144)

Method bindParam()

 Maps a place holder with a value.

 Possibility to specify a variable type.

 Anonymous place holder:

 Named place holder:

$sql = 'SELECT id, firstName FROM members WHERE id = :id';

$select = $c->prepare($sql);

$select->bindParam(':id', $id, PDO::PARAM_INT);

$sql = 'SELECT id, firstName FROM members WHERE id = ?';

$select = $c->prepare($sql);

$select->bindParam(0, $id, PDO::PARAM_INT);

(145)

Place holders

 Specify expected values

 PDO::PARAM_STR

 PDO::PARAM_INT

 PDO::PARAM_NULL

 PDO::PARAM_LOB

 PDO::PARAM_BOOL

 If PDO::PARAM_STR, possibility to specify the maximum length of the string.

(146)

Disconnecting

 Destroying PDO object

 That’s all Folks!

unset($c);

(147)

Stop-and-think

Do you have any questions?

(148)

You have successfully completed the SUPINFO refresher course :

PHP

(149)

The end

Practice is the best way to learn

Enjoy PHP 6 Soon …

Références

Documents relatifs

CREATE TABLE IF NOT EXISTS pays ( id_pays char(3) NOT NULL, nom_pays varchar(50) NOT NULL, PRIMARY KEY (id_pays). ) ENGINE=InnoDB DEFAULT

Une jointure est la concaténation des champs d'une table avec ceux d'une autre table et la.. concaténation de chaque enregistrement de la table 1 avec tous ceux de la table 2 quand

La page doit contenir toutes les données présentes, toutes les règles de gestion de la page, tous les traitements effectués ainsi que leurs algorithmes, et tous les noms des

Ce problème est fondamental : on a précisément recours à PHP (ou à d’autres langages s’exécutant sur le serveur) parce-que c’est le seul moyen d’agir sur des fichiers sur

Les cookies sont envoy´es par le serveur dans les entˆetes HTTP ` a l’aide de la directive Set-Cookie. Un cookie a normalement une date de validit´e qui assure sa suppression par

Supposons qu’Alice et Bob veulent collaborer sur le projet super-proj - Alice possède le code initial qu’elle publie sur son dépôt gitlab : https://gitlab.com/alice/super-proj.git

Si les tableaux passés en arguments ont les mêmes clés (chaînes de caractères), les valeurs sont alors rassemblées dans un tableau, de manière récursive, de façon à ce que, si

Les accolades sont facultatives dans certaines situations (par exemple s'il n'y a qu'une seule instruction dans un &#34;if&#34;) mais je vous recommande de systématiquement les