By W. Jason Gilmore
m
tech facts at your fingertips
dz.co CONTENTS INCLUDE:
■ Confi guration
■ Popular PEAR Packages
r
efcar
PHP
■ Object-Oriented PHP
■ Regular Expressions
■ MySQL Integration
■ Hot Tips and more...
By W. Jason Gilmore
ABOUT THIS REFCARD
POPULAR PEAR PACKAGES
PHP is the world's most popular server-side Web scripting
The PHP Extension Application Repository (PEAR) is the de facto
language, sporting a syntax simple enough to attract novice
service for distributing reusable PHP components. Over 500
programmers yet powerful enough to run some of the world's
packages are available for download from http://pear.php.net/,
most popular websites, among them Yahoo!, Facebook,
including these popular solutions:
GameSpy, and Vimeo.
PEAR Packages
Description
This reference card was created to help you quickly navigate
Auth
Facilitates authentication against IMAP, LDAP, plaintext fi les,
some of PHP's most commonplace features, including object-
most modern databases, RADIUS, and other authentication
oriented programming, array and string manipulation, regular
solutions.
expressions, and MySQL integration.
Confi g
Aids in the management of application confi guration data
HTML_QuickForm2 Streamlines the creation, processing, and validation of HTML
forms.
CONFIGURATION
HTML_Table
Simplifi es the generation of dynamic HTML tables
HTTP_Upload
Assists in the management of fi les uploaded through an
PHP's behavior can be confi gured at a variety of levels:
HTML form.
Mail
Facilitates transmission of e-mail through a website by
Global Confi guration
supporting multiple mailer backends (including PHP's native
The php.ini fi le is PHP's confi guration fi le, containing more
mail() function, Sendmail, and SMTP)
than 200 directives capable of tweaking nearly every aspect of
MDB2
A database abstraction layer supporting numerous
the language's behavior. This fi le is parsed every time PHP is
databases, including MySQL, PostgreSQL, Oracle, and MS
Subscribe Now for FREE!
SQL.
invoked, which for the server module version occurs only when
m
Net_UserAgent_
Provides information regarding the user's browser and
the web server starts, and every time for the CGI version.
Detect
operating system.
PHPDocumentor
Automates the code documentation creation and
e.co
Host- and Directory-specifi c Confi guration
management process
If you lack access to the php.ini fi le, you may be able to change
PHPUnit
Aids in the creation, execution and analysis of application
zon
desired directives within Apache's httpd.conf or .htaccess fi les.
tests
For instance, to force the display of all PHP errors for solely your
XML_RPC
Supports creation of PHP-driven XML-RPC clients and
.
d
servers.
w
development domain (for instance http://dev.wjgilmore.com),
add the following to a .htaccess fi le:
ww
php_fl ag display_errors on
POPULAR FRAMEWORKS
Web frameworks help the programmer to embrace best practices,
Hot
Each directive is assigned one of three permis-
simultaneously decreasing errors and eliminating redundant code.
Tip
sion levels (PHP_INI_ALL, PHP_INI_PER_DIR, PHP_
INI_SYSTEM) which determines where it can be
If you haven't yet settled upon a framework, consider checking out
set. Be sure to consult the PHP documentation
one or several of the following popular solutions:
before tweaking settings outside of the php.ini fi le. See
http://www.php.net/ini for a complete list of directives.
Get More Refcardz
(They’re free!)
Script-specifi c Confi guration
■
Occasionally you'll want to tweak directives on a per-script basis.
Authoritative content
For instance to change PHP's maximum allowable execution
■ Designed for developers
time for a script tasked with uploading large fi les, you could call
■ Written by top experts
the ini_set() function from within your PHP script like so:
■
ini_set('max_execution_time', 60);
Latest tools & technologies
■ Hot tips & examples
Changing the PHP File Extension
■ Bonus content online
PHP's default fi le extension is .php, however you can change it
■
to whatever you please by adding the desired extension to the
New issue every 1-2 weeks
AddType directive within Apache's httpd.conf fi le. For instance to
Subscribe Now for FREE!
confi gure Apache to recognize .dzone as a supported PHP fi le
extension:
Refcardz.com
PHP
AddType application/x-httpd-php .php .dzone
DZone, Inc. | www.dzone.com
2
PHP
tech facts at your fingertips
Popular Frameworks, continued
Object-Oriented PHP, continued
Framework
Source
Class Constants
CakePHP
http://www.cakephp.org/
Class constants are defi ned with the const keyword, and can
CodeIgniter
http://www.codeigniter.com/
be referenced through the scope resolution operator (::). For
eZ Components
http://ez.no/ezcomponents
instance, to defi ne a constant identifying the RadioStation class'
Prado
http://www.pradosoft.com/
minimum supported PHP version:
symfony
http://www.symfony-project.org/
Zend Framework
http://framework.zend.com/
const MIN_PHP_VER = '5.3';
You can then reference it outside the class like so:
OBJECT-ORIENTED PHP
echo RadioStation::MIN_PHP_VER;
Extending Classes
Creating a Class
Class hierarchies can be created using the extends keyword. For
A class defi nes the behavior and characteristics of an entity you'd
instance, an application tasked with cataloging all major media
like to represent in an application. A sample class follows:
outlets might fi rst defi ne a MediaOutlet class which defi nes
class RadioStation {
private $_id;
some broad characteristics, and then child classes such as
private $_name;
RadioStation and TVStation would inherit from it:
private $_frequency;
private $_band;
class MediaOutlet {
private $_audioStream;
protected $owner;
protected $residentCountry;
public function setBand($band) {
$this->_band = $band;
public function setOwner($owner) {
}
...
}
public function getBand() {
}
return $this->_band;
class RadioStation extends MediaOutlet {
}
...
...
}
}
If you wanted to prevent child classes (in this case,
Object Instantiation
RadioStation) from overriding a parent method, prefi x it with
To create an instance of a class (known as an object), you call the
the fi nal keyword. For instance:
class name like you would a function, preceding it with the new
fi nal public function setOwner($owner) {
keyword:
...
}
$wtvn = new RadioStation();
Class Constructors
Class Abstraction
Constructors are useful for performing initialization tasks at
The aforementioned MediaOutlet class would be more
class instantiation time, thereby saving you the hassle of calling
accurately defi ned as an abstract class, because it would never
additional class methods. Constructors are declared using the
be explicitly instantiated (instead, one would instantiate derived
classes such as RadioStation, TVStation, Newspaper, etc.).
__construct() method, like so:
Abstract classes are declared using the abstract keyword:
function __construct($id="") {
// If specifi c station ID is requested, retrieve it
abstract class MediaOutlet {
from the database
...
if (isset($id))
}
$this->fi nd($id);
}
You can choose to override any methods found within an
abstract class, which would then be inherited by its child classes,
Class Destructors
or alternatively you can declare them as abstract, requiring these
Custom class destructors can perform tasks when the object is
methods be defi ned by any child.
destroyed. You can create a destructor using the __destruct()
method:
Creating Interfaces
function __destruct() {
An interface helps developers rigorously enforce application
printf("The radio station %s has been destroyed!",
specifi cations, and is similar to an abstract class, but contains
$this->name);
}
solely the required method signatures. Any class implementing
the interface must also implement all defi ned interface methods.
Attribute and Method Visibility
Interfaces are defi ned using the interface keyword and their
PHP supports three levels of attribute and method visibility:
names are typically prefi xed with a capital I:
interface IRadioStation {
Attribute and
Description
Method Visibility
public function setBand($band);
public function getBand();
Public
Public attributes and methods can be accessed anywhere
}
Private
Private attributes and methods are only accessible within
the class that defi nes them
class RadioStation implements IRadioStation {
Protected
Protected attributes and methods are available to the class
...
and its subclasses.
}
DZone, Inc. | www.dzone.com
3
PHP
tech facts at your fingertips
Multidimensional Arrays, continued
WORKING WITH ARRAYS
Referencing an element isn't unlike the methods used for
The array is one of programming's most powerful data structures,
indexed and associative arrays; it's just a tad more verbose:
capable of managing a seemingly endless variety of data.
$channel = $stations["FM"]["WTVN"];
Creating an Array
Determining Array Size
The following two examples all create an array named $stations
The number of elements found in an array can be determined
consisting of three elements:
using the count() function:
// Outputs "3 stations are being tracked"
$stations = array (
printf("%d stations are being tracked",
"WTVN",
count($stations));
"WBNS",
"WYTS");
Sorting Arrays
$stations = array();
PHP offers a powerful assortment of functions (more than 70)
$count = array_push($stations, "WTVN", "WBNS", "WYTS");
capable of sorting arrays in a variety of ways. Most of these
You can create an array consisting of a character- or numerically-
functions accept an optional parameter which can change the
based range using the range() function:
sorting behavior. Four values are supported, including SORT_
// $teenListenerDemographic =
REGULAR for comparing elements without implicit typecasting,
// array(13,14,15,16,17,18,19)
SORT_NUMERIC for comparing elements numerically, SORT_STRING
$teenListenerDemographic = range(13,19);
for comparing elements as strings, and SORT_LOCALE_STRING, for
sorting elements according to the defi ned locale.
Retrieving Array Contents
Description
Function
Indexed arrays such as those created so far can be accessed
according to their numerical offset (beginning with a zero-
Sort an array while maintaining the
bool asort(array &$array [, int $sort_fl ags])
key association
based offset). For instance to retrieve the second value in the
Reverse sort an associative array
bool arsort(array &$array [, int $sort_fl ags])
$stations array:
while maintaining key association
$callSignal = $stations[1];
Sort an associative array by key,
bool ksort(array &$array [, int $sort_fl ags])
maintaining index association
Perhaps the most fl exible way to enumerate array contents is
Reverse sort an associative array by
bool krsort(array &$array [, int $sort_fl ags])
through the foreach statement:
key, maintaining index association
foreach($stations AS $station)
Sort an array case-insensitively in an
bool natcasesort($array &array)
printf("%s<br />", $station);
order logically presumed by humans
Sort an array in an order logically
bool natsort(array &$array)
Associative Arrays
presumed by humans
Associative arrays give developers the opportunity to assign
Sort an array in reverse order
bool rsort(array &$array [, int $sort_fl ags])
meaningful context to both the array value and its corresponding
Sort an array according to the
bool usort(array &$array, callback
key:
specifi cations of a user-defi ned
$comparison_function)
function
$stations = array(
Sort an array according to the
bool uasort(array &$array, callback
"WTVN" => "610",
specifi cations of a user-defi ned
$comparison_function)
"WBNS" => "1460",
function, maintaining index
"WYTS" => "1230 "
association
);
Key sort an array according to the
bool uksort(array &$array, callback
specifi cations of a user-defi ned
$comparison_function)
You can then obtain a value (in this case the station/band) by
function
referencing its call signal:
Consult the PHP manual for a complete listing: http://www.php.
// $channel = "610"
net/array.
$channel = $stations["WTVN"];
The foreach statement proves equally useful for navigating
STRING PARSING
associative arrays:
foreach($stations AS $key => value)
PHP supports over 100 functions identifi ed as specifi c to string
printf("%s => %s<br />", $key, $value);
parsing and manipulation. Following are the most commonly
Multidimensional Arrays
used tasks.
Multidimensional arrays are useful for representing more
Description
Function
complex data structures:
Converting an array
$stations = array("WTVN","WBNS","WYTS");
to a string
$stations = implode(",", $stations)
$stations = array(
// $stations = "WTVN,WBNS,WYTS"
"AM" =>
Converting a string
$stations = "WTVN,WBNS,WYTS";
array("WTVN" => "610",
to an array
$stations = explode(",", $stations);
"WBNS" => "1460",
// $stations[0]="WTVN", $stations[1]="WBNS",
$stations[2]="WYTS"
"WYTS" => "1230"),
"FM" =>
Counting words in
$sentence = "Columbus is home to numerous
a string
radio stations";
array("WLVQ" => "96.3",
$words = str_word_count($sentence);
"WNCI" => "97.9")
// $words = 7
);
See also: count_chars()
DZone, Inc. | www.dzone.com
4
PHP
tech facts at your fingertips
String Parsing, continued
Metacharacters
\A
Match only beginning of string
Description
Function
\b
Match a word boundary
Converting
$callsign = strtoupper("wtvn");
a string to
\B
Match anything but word boundary
// $callsign = "WTVN"
uppercase
See also: lcwords(), strtolower(), ucfi rst(),
\d
Match a digit character
ucwords()
\D
Match a non-digit character
Strip HTML and PHP
$input = "You won the <a href="http://www.
\s
Match a whitespace character
tags from a string
example.com">lottery!</a>."
$clean = strip_tags($input);
\S
Match a non-whitespace character
// $clean = "You won the lottery!"
[]
Enclose a character class
See also: htmlentities(), htmlspecialchars()
()
Enclose a character grouping or defi ne backreference
Replace all
$phrase = "Big rockers listen to rock radio";
$
Match end of line
occurrences of a
$phrase = str_replace("rock", "talk", $phrase);
substring
// $phrase = "Big talkers listen to talk radio"
^
Match beginning of line
See also: substr_replace(), strireplace(),
.
Match any character except for newline
strtr()
\
Quote the next metacharacter
Return part of a string $description = "WFAN: Sports Radio 66";
as specifi ed by an
$callsign = substr($description, 0, 4);
\w
Match any string containing underscore and alphanumeric
offset
See also: strrchr()
characters
\W
Match a string containing anything but underscore and
Compare two strings if (strcasecmp("WTVN", "wtvn") == 0)
alphanumericl characters
case-insensitively
echo "The strings are equal in a case-
insensitive context."
POSIX Regular Expression Functions
See also: strncasecmp()
PHP supports seven functions as defi ned by the POSIX 1003.2
Convert newline
$stations = "WTVN: 610\nWLW: 700\nWYTS: 1230";
specifi cation, including these commonly used solutions:
characters to the
$html = nl2br($stations);
HTML <br /> tag
// $html = "WTVN: 610<br />WLW: 700<br />WYTS:
int ereg(str $pattern, str $string
Search $string for a $pattern. You can optionally
1230"
[, array &$regs])
include the $regs parameter, which will cause
See also: htmlentities(), htmlspecialchars()
an array of the same name to be returned
containing each match. See eregi() for case-
insensitive counterpart.
string ereg_replace(str
Replace any patterns found in string with
REGULAR EXPRESSIONS
$pattern, str $replacement, str
replacement. See eregi_replace() for case-
$string)
insensitive counterpart.
array split(str $pattern, str
Split $string into an array, dividing it according
PHP's regular expression features borrow heavily from both the
$string [, int $limit])
to $pattern. See spliti() for case-insensitive
Perl and POSIX formats, and in fact are formal y identifi ed as
counterpart.
such.
POSIX Regular Expression Syntax
Perl-compatible (PCRE) Regular Expression Functions
PHP supports eight PCRE-specifi c functions, including these
[0-9]
Any decimal digit from 0 - 9
commonly used solutions:
[a-z]
Any character from lowercase a through lowercase z
[A-Z]
Any character from uppercase A through uppercase Z
Function
Description
[A-Za-z]
Any character from upper case A through lowercase z
array preg_grep(str
Searches $subject for $pattern, returning an array of
p+
Any string containing at least one p
$pattern, array $subject
matches. The optional $fl ags parameter can be set to
p*
Any string containing zero or more p's
[, int $fl ags])
PREG_GREP_INVERT, causing an array consisting of
unmatched elements to be returned.
p?
Any string containing zero or one p
p{N}
Any string containing sequence of two p's
int preg_match(str
Determines whether $pattern exists in $subject. If
$pattern, str $subject [,
$matches is defi ned, a similarly named variable will
p{N,M}
Any string containing sequence of between N and M p's
array &$matches [, int
be returned containing the matches. If $fl ags is set to
p{2,}
Any string containing sequence of at least two p's
$fl ags [, int $offset]]])
PREG_OFFSET_CAPTURE, the string offset value will
also be returned for each match. See preg_match_all()
p$
Any string with p at the end of it
for a variation of this function.
^p
Any string with p at the beginning of it
[^a-zA-Z]
Any string not containing characters a-z through A-Z
mixed preg_
Searches $subject for $pattern, replacing any
replace(mixed $pattern,
instances with $replacement. See preg_replace_
p.p
Any string containing p followed by any character, followed by
mixed $replacement,
callback() for a variation of this function.
another p
mixed $subject [, int
$limit [, int &$count]])
Regular Expression Examples
Validating a Phone Number
Common PCRE Pattern Modifi ers
Presumes the required format is XXX-XXX-XXXX.
Modifi er
Description
// PCRE
g
Perform a global search
if (preg_match('/^[2-9]{1}\d{2}-\d{3}-\d{4}$/', '614-
599-2599'))
i
Perform a case-insensitive search
echo "Valid number!";
m
Treat the string as multiple lines (
// POSIX
s
Ignore newline characters
if (ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', '614-
x
Ignore white space and comments
999-2599'))
u
Stop at the fi rst match (ungreedy search)
echo "Valid number!";
DZone, Inc. | www.dzone.com
5
PHP
tech facts at your fingertips
Validating a Username
Telling Time with PHP, continued
Presumes username is between 6 and 10 alphabetical and
Month Parameters
numerical characters.
F
Full text representation of month
// PCRE
m
Numeric representation of month
if (preg_match('/^[a-z0-9]{6,10}$/i', '800gilmore'))
echo "Valid username!";
M
Three letter textual representation of month
// POSIX
n
Numeric representation of month, without leading zeros
if (eregi('^[a-z0-9]{6,10}$', '800gilmore'))
t
Number of days in given month
echo "Valid username!";
Year Parameters
Turn URLs into hyperlinks
L
Whether date is a leap year
// PCRE
o
ISO-8601 year number
$text = "Go to http://www.wjgilmore.com.";
Y
Full numeric representation of year
$html = preg_replace('/\s(\w+:\/\/)(\S+\.?)(\w+)/',
y
Two digit representation of year
' <a href="\\1\\2\\3">\\1\\2\\3</a>', $text);
// POSIX
Date Function Examples
$text = "Go to http://www.wjgilmore.com. ";
$html= ereg_replace('[a-zA-Z]+://(([.]?[a-zA-
July 29, 2008
print date('F j, Y');
Z0-9_/-])*)', '<a href="\\0">\\0</a>', $string);
7/29/08
print date('m/j/y');
// $html = "Go to <a href=" http://www.wjgilmore.
Today is Tuesday, July 29 10:45:21am
printf("Today is %s", date('l, F j h:i:sa'));
com">http://www.wjgilmore.com."
There are 31 days in July.
printf("There are %d days in %s.",
date('t'), date('F'));
TELLING TIME WITH PHP
Setting the Timezone
The Date Function
You can set the timezone for all scripts by setting the date.
timezone confi guration directive within the php.ini fi le, or on
The date() f unction is perhaps one of PHP's most commonly
a per-script basis using the date_default_timezone_set()
used functions, capable of retrieving nearly every temporal
function.
attribute of a specifi c timestamp.
string date(string $format [, $int $timestamp])
Other Useful Functions
a
Lowercase Ante meridiem and Post meridiem
Function
Description
A
Uppercase Ante meridiem and Post meridiem
int mktime([int $hour [, int $min [, int
Returns the Unix timestamp for a given
$sec [, int $month [, int $day [, int $year date
B
Swatch Internet Time
[, int $is_dst]]]]]]])
c
ISO 8601 date
int time()
Returns current timestamp
e
Timezone identifi er
string setlocale(int $category, string
Sets the script locale
g
12-hour hour format without leading zeros
$locale)
G
24-hour hour format with leading zeros
int strtotime(string $time [, int $now])
Converts English textual date/time
h
12-hour hour format with leading zeros
description into a Unix timestamp
H
24-hour hour format with leading zeros
bool checkdate(int $month, int $day,
Validates the date composed by the
i
Minutes with leading zeros
int $year)
$month, $day, and $year arguments.
I
Specifi es whether date is in daylight savings time
array getdate([int $timestamp])
Retrieves a timestamp as an associative
array. Associative keys include seconds,
O
Difference to Greenwich time (GMT) in hours
minutes, hours, mday (day of the
P
Difference to Greenwhich time (GMT) with colon between hours and
month), wday (day of week), mon
minutes
(month), year, yday (day of the year),
r
RFC 2822 date
weekday, month, and 0 (seconds since
UNIX Epoch)
s
Seconds, with leading zeros
T
Timezone abbreviation
PHP 5.1.0 introduced an object-oriented DateTime class. See
u
Milliseconds
http://www.php.net/DateTime for more information.
U
Seconds since Unix Epoch
Date-related Examples
z
Timezone offset in seconds
Output "December 25 $date = date('l', mktime(0,0,0,12,25,2008));
Day Parameters
falls on a Thursday"
printf("December 25 falls on a %s", $date);
d
Day of month, two digits with leading zeros
Output "Next month is printf("Next month is %s", date('F', strtotime('+1
August."
month')));
D
Three letter textual representation of day
j
Day of month without leading zeros
Output "Last Friday
$date = date('F d, Y', strtotime('Last Friday'));
fell on July 25, 2008"
printf("Last Friday fell on %s", $date);
l
Textual representation of day
Output "Oggi è
setlocale(LC_ALL, "it_IT");
N
ISO-8601 numeric representation
martedì"
printf("Oggi è %s", strftime("%A"));
S
Two character English ordinal suffi x for day of month
Retrieve a page's last-
echo date('l, F j h:i:sa', fi lemtime($_SERVER["SCRIPT_
w
Numeric representation of day of week
modifi ed date
NAME"]));
z
Numerical offset of day of year
Calculate the
$date1 = strtotime("2008-08-14");
difference between
Week Parameters
$date2 = strtotime("2008-07-11");
two dates
$diff = $date2 - $date1;
W ISO-8601
week number of year
printf("Difference in days: %s", $diff / 60 / 60 / 24);
DZone, Inc. | www.dzone.com
6
PHP
tech facts at your fingertips
Retrieving data as an indexed array:
MYSQL INTEGRATION
while ($row = $result->fetch_row() {
printf("%S", $row[0]);
Although PHP supports several popular databases, MySQL
}
remains by far the most common database solution. PHP's
Retrieving data as an object:
MySQL support has evolved considerably in recent years, with
while ($row = $result->fetch_object() {
the MySQLi (MySQL Improved) extension being the current
printf("%S", $row->callsign);
recommended solution. Here are the most commonly used
}
methods.
Determining the Number of Rows Affected and Retrieved
The PHP 5.3 release includes a new MySQL
To determine the number of affected rows after sending an
Hot
INSERT, UPDATE, or DELETE query, use the affected_rows
Tip
driver known as mysqlnd (MySQL Native Driver).
property.
This driver eliminates the need for a previously
required special licensing exception (FLOSS), and
Example:
eliminates the need to have MySQL installed on the same ma-
$result = $mysqli->query("UPDATE stations SET station =
chine as PHP. It has already been integrated with the mysql
'610' WHERE callsign = 'WTVN'");
printf("Rows affected: %d", $result->rows_affected);
and mysqli extensions, with PDO support in the works.
To determine how many rows were returned when using a
SELECT query, use the num_rows property:
Connecting to MySQL
$result = $mysqli->query("SELECT * FROM stations WHERE
The mysqli extension provides a number of ways to connect to
state ='Ohio');
MySQL, but the easiest involves just passing the connection data
printf("Rows affected: %d", $result->num_rows);
along when instantiating the mysqli class:
Working with Prepared Statements
mysqli new mysqli([string host [, string user [, string
pswd
Prepared statements both optimize query performance and
[string dbname [int port [string socket]]]]]]);
decrease the possibility of SQL injection attacks by separating
the query data from the logic, fi rst passing the query to MySQL
Here's an example:
for preparation, binding variables to the query columns, and
$mysqli = new mysqli("localhost", "webuser", "secret",
"corporate");
fi nally passing the data to MySQL for query execution.
Handling Connection Errors
To prepare a query, create the query, and then initialize a
statement object using the stmt_init() method:
In case of connection error you can retrieve both the error
$query = "INSERT INTO stations VALUES(?, ?)";
number and error string using the errno() and error()
methods. Example:
$stmt = $mysqli->stmt_init();
if ($mysqli->errno) {
Next the query is prepared by passing it to MySQL using the
printf("Unable to connect: %s", $mysqli->error);
prepare() method:
exit();
$stmt->prepare($query);
}
Next, bind the parameters using the bind_param() method:
Sending a Query to the Database
$stmt->bind_param('ss', "WTVN", "610");
Once the connection has been established, you can begin
Finally, execute the prepared statement using the execute()
querying the database. Queries are sent using the query()
method:
method:
$stmt->execute();
mixed query(string $query [, int $resultmode])
You can also use prepared statements to retrieve results. The
Setting the optional $resultmode parameter to MYSQLI_USE_
general process used to execute the previous INSERT query is
RESULT will cause query() to return the result as an unbuffered
identical to that required for executing a SELECT query, except
set.
that the bind_param() method is not required, and you bind
Example:
results following a call to the execute() method. An example
$result = $mysqli->query("SELECT callsign FROM
follows:
stations");
$query =
"SELECT callsign, frequency FROM stations
Sending INSERT, UPDATE, and DELETE queries works
ORDER BY callsign";
identically. For instance, sending an UPDATE query works like
$stmt = $mysqli->stmt_init();
this:
$stmt->prepare($query);
$result = $mysqli->query("UPDATE stations SET station
$stmt->execute();
= '610' WHERE callsign = 'WTVN'");
$stmt->bind_result($callsign, $frequency);
while ($stmt->fetch())
Retrieving Data
printf("%s: %s<br />", $callsign, $frequency);
Data can be parsed from the result set using a number of data
structures, including via associative and indexed arrays, and
Transactions
objects.
By default the MySQLi extension will render each query
Retrieving data as an associative array:
"permanent" upon successful execution, actually changing the
while ($row = $result->fetch_array(MYSQLI_ASSOC) {
database's contents when INSERT, UPDATE, and DELETE queries
printf("%S", $row["callsign"]);
are processed. However the success of some tasks depend upon
}
the successful execution of several queries, and until all have
DZone, Inc. | www.dzone.com
7
PHP
tech facts at your fingertips
Transactions, continued
USEFUL ONLINE RESOURCES
successfully executed, no changes to the database should actually
occur. ATM transactions and online credit card processing are
common examples requiring several queries. Using transactions,
Resource
Source
you can change the MySQLi extension's behavior, committing a
PHP Zone
http://php.dzone.com
series of queries as you see fi t.
The PHP Website
http://www.php.net
To begin a transaction, start by disabling the autocommit feature:
Zend Developer Zone
http://devzone.zend.com/
$mysqli->autocommit(FALSE);
PlanetPHP
http://www.planet-php.net/
Execute the various queries as you see fi t, and if everything
proceeds as you expect, execute the commit() method:
PHPDeveloper.org
http://phpdeveloper.org/
$mysqli->commit();
Developer.com
http://www.developer.com/
Otherwise, if a problem occurs, execute the rollback() method:
ONLamp PHP Devcenter
http://www.onlamp.com/php/
$mysqli->rollback();
A B O U T T H E A U T H O R
R E C O M M E N D E D B O O K
W. Jason Gilmore
Beginning PHP and MySQL is
Jason Gilmore is founder of W.J. Gilmore, LLC, providing web development,
the defi nitive book on the PHP
consulting, and technical writing services to clientele ranging from publicly
language and MySQL database.
traded corporations to small startups. Jason is a prolifi c contributor to a
Readers are treated to compre-
number of leading publications such as Developer.com, Linux Magazine,
hensive introductions of both
and TechTarget, with almost 100 articles to his credit. He's cofounder of the
technologies, and in addition to
CodeMash conference (http://www.codemash.org/), a non-profi t organiza-
in-depth instruction regarding
tion charged with organizing the annual namesake event.
using these two technologies in
Publications
unison to build dynamic web sites.
■ Beginning PHP and MySQL
■ Beginning PHP and PostgreSQL 8 with Robert H. Treat
■ Beginning PHP and Oracle
Website
BUY NOW
http://www.wjgilmore.com
books.dzone.com/books/phpsql
Want More? Download Now. Subscribe at refcardz.com
Upcoming Refcardz:
Available:
■
Core CSS: Part II
Published September 2008
Published June 2008
FREE
■
Getting Started with JPA
■
Core CSS: Part III
■
jQuerySelectors
■
Core CSS: Part I
■
SOA Patterns
■
Flexible Rails: Flex 3 on Rails 2
■
Struts 2
■
Scalability and High
Published May 2008
Published August 2008
■
Agile Methodologies
■
■
Windows PowerShell
Very First Steps in Flex
■
■
C#
Dependency Injection in EJB 3
■
Spring Annotations
■
Groovy
■
Core Java
■
Core .NET
Visit http://refcardz.dzone.com
■
JUnit
Published July 2008
for a complete listing of
■
MySQL
■
NetBeans IDE 6.1 Java Editor
available Refcardz.
■
Seam
■
RSS and Atom
Design Patterns
■
GlassFish Application Server
Published June 2008
■
Silverlight 2
■
IntelliJ IDEA
DZone, Inc.
ISBN-13: 978-1-934238-27-1
1251 NW Maynard
ISBN-10: 1-934238-27-9
Cary, NC 27513
5 0 7 9 5
888.678.0399
DZone communities deliver over 3.5 million pages per month to
919.678.0300
more than 1.5 million software developers, architects and designers.
Refcardz Feedback Welcome
DZone offers something for every developer, including news,
refcardz@dzone.com
tutorials, blogs, cheatsheets, feature articles, source code and more.
Sponsorship Opportunities
9 781934 238271
$7.95
“DZone is a developer’s dream,” says PC Magazine.
sales@dzone.com
Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,
Version 1.0
photocopying, or otherwise, without prior written permission of the publisher. Reference: Beginning PHP and MySQL, Jason Gilmore, Apress, 2008.