How to exploit PHP abilities?
www.supinfo.com
Copyright © SUPINFO. All rights reserved
Course objectives
Understand the PHP syntax
Use the PHP abilities
By completing this course, you will:
Course topics
Basic syntax
Control Structures
Functions
Arrays
These are the parts that we will approach:
Basic Syntax
Understand the PHP code’s architecture
Preview
Markups and commentaries
Variables
Types
Operators
These are the chapters that we will approach :
PHP instructions are put between markups:
<?php … ?>
Other markups to proscribe:
<? … ?>
<% … %>
<script language="php">…</script>
Markups and commentaries
Commentaries
// just one line /* several
lines */
Casse sensitive
Prefixed by a $ (dollar)
Authorized:
$_var;
$var;
$Var;
Forbidden:
$123var;
Variables
Declaration
Concatenation
Destruction
Variables
$var = "value";
$var = $foo . $bar;
$var = $foo . "word";
unset($var);
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
Mathematics operators:
+ - * / % ++ --
Comparison operators:
== === !=
<> < <= > >=
Logical operators:
&& ||
Operators
Stop-and-think
Do you have any questions?
Control structures
Preview
if … elseif ... else
switch
while, do ... while
for
foreach
break
continue
These are the chapters that we will approach :
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 }
if … elseif … else
Ternary operator (Equivalent to if … else)
elseif enables to do several different tests.
if ($str == "Hello") { // Code
} elseif ($str == "Bye") { // Code
} else {
// Code }
(condition) ? Instr if TRUE : Instr if FALSE
Similar to if … elseif … else
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
Loops while the condition is true
At least one execution…
while ($int < 10) { echo $int++;
}
Loops
$int = 1;
do {
echo $int;
} while ($int < 0);
For
Foreach
for ($i = 0 ; $i < 10 ; $i++) {
echo $i;
}
Loops
$array = array('apple', 'lemon', 'mangoe');
foreach ($array as $key => $value) {
echo $key . " : " . $value;
}
Break
Continue
while ($int++ < 10) { break;
}
Special behavior
for ($i = 0 ; $i < 10 ; $i++) {
if ($i == 1) continue;
echo $i;
}
Stop-and-think
Do you have any questions?
Functions
Preview
Functions’ declaration
Functions’ use
These are the chapters that we will approach :
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
Use of an external variable
$i = 0;
function foo() {
global $i;
$i += 10;
}
foo();
echo $i; // displays 10
Global Keyword
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
Stop-and-think
Do you have any questions?
Arrays
Preview
Declaration
Use
Some functions on arrays
These are the chapters that we will approach :
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
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 )
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
Count the elements of the array
The sizeof() function is a count() alias.
Functions : count() and sizeof()
sizeof($fruits); // 3 count($fruits); // 3
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
Stop-and-think
Do you have any questions?
www.supinfo.com
Copyright © SUPINFO. All rights reserved
Data’s appropriation.
Handle data from an user.
Keep informations about an user.
Send an email.
By completing this course, you will be able to:
Course objectives
Preview
GET & POST methods
Predefined variables
Cookies
Sessions
Mail function
These are the chapters that we will approach :
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
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:
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);
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']);
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 :
Stop-and-think
Do you have any questions ?
Discover the main functions proposed by PHP
www.supinfo.com
Copyright © SUPINFO. All rights reserved
Course topics
Inclusion functions
Dates management
Buffering functions
String functions
Array functions
Manipulation of files These are the parts that we will approach :
Inclusion functions
Preview
Utility of an inclusion function
Difference between include() and require()
Function include() and require()
These are the chapters that we will approach :
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.
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.
Stop-and-think
Do you have any questions?
Dates management
Preview
The UNIX timestamp
Function time()
Function date()
These are the chapters that we will approach :
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.
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. ?>
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.
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
Stop-and-think
Do you have any questions?
Buffering functions
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 :
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.
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 ...
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. ?>
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. ?>
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. ?>
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. ?>
Stop-and-think
Do you have any questions?
String functions
Preview
Function strlen()
Function substr()
Function str_replace()
These are the chapters that we will approach :
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. ?>
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.
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. ?>
Stop-and-think
Do you have any questions?
Array functions
Preview
Function array_push()
Function array_unshift()
Function array_pop()
Function array_shift()
Function sort()
These are the chapters that we will approach :
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 )
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 )
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 )
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 )
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 )
Stop-and-think
Do you have any questions?
Manipulation of files
Preview
Opening a file
Simplified reading
Simplified writing
Copy of a file
Deleting a file
These are the chapters that we will approach :
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.
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
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. ?>
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. ?>
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. ?>
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. ?>
Stop-and-think
Do you have any questions?
Object-Oriented Programming with PHP
www.supinfo.com
Copyright © SUPINFO. All rights reserved
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:
Course topics
Basics.
Exceptions controls
Course’s plan :
Basics
At the beginning of OOP
Course topics
OOP in real world.
Basic syntax
Constructors and Destructors
Member visibility
Static keywords Course’s plan :
OOP in real world
OOP Terms :
Class:
– vehicle;
Objects:
– car;
Methods:
– Move;
Properties:
– Color.
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
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
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
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
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
Member visibility
public:
Reachable from everywhere.
protected:
Reachable from the class itself and its extended classes.
private:
restricts the access to the class itself
.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
Stop-and-think
Do you have any questions?
Exceptions controls
Course topics
Some functions
Error managment Course’s plan :
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
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. }
Stop-and-think
Do you have any questions?
How to interact with databases in PHP
Campus-Booster ID : 51461
Course objectives
Learn about MySQL
Be able to interact with databases using PHP
By completing this course, you will:
Course topics
Presentation of MySQL
Using mysql_ functions
Using PDO extension Course’s plan:
Presentation
Preview
Presentation.
Discovering PHPMyAdmin
These are the chapters that we will approach:
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!
PHPMyAdmin
Discoverin g
PHPMyAd min
Stop-and-think
Do you have any questions?
How to connect to a MySQL database in PHP 4 and 5
Preview
Connecting to the database
Executing requests
These are the chapters that we will approach:
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);
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);
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);
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. }
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. }
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.';
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);
Stop-and-think
Do you have any questions?
PHP 5 extension, PHP 6 standard
Preview
Presentation and advantages.
How to use it?
These are the chapters that we will approach:
P HP D ata
O bject
Presentation
Advantages
Abstraction of database server nature
Object oriented aspect (different from mysql_ functions)
Using exceptions
PHP 6 standard, PHP 5 extension
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);
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);
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, '' , '');
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)
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. }
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.
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;
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);
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();
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"
) ) */
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.
Fetch Styles
Using
PDO::FET CH_CLAS S
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';
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);
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.
Disconnecting
Destroying PDO object
That’s all Folks!
unset($c);
Stop-and-think
Do you have any questions?
You have successfully completed the SUPINFO refresher course :
PHP
The end
Practice is the best way to learn
Enjoy PHP 6 Soon …