DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. PHP 5.4
refcard cover
Refcard #023

PHP 5.4

Scripting with PHP

Covers many important aspects of the simple, yet powerful, scripting language.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Jason Gilmore
developer, bestselling author, WJ Gilmore, LLC
Table of Contents
► About This Refcard ► Popular Pear Packages ► Popular Frameworks ► Object-Oriented PHP ► Working with Arrays ► String Parsing ► Regular Expressions ► Telling Time with PHP ► MySQL Integration ► Useful Online Resources
Section 1

About This Refcard

By W. Jason Gilmore

PHP is the world's most popular server-side Web scripting language, sporting a syntax simple enough to attract novice programmers yet powerful enough to run some of the world's most popular websites, among them Yahoo!, Facebook, GameSpy, and Vimeo.

This reference card was created to help you quickly navigate some of PHP's most commonplace features, including objectoriented programming, array and string manipulation, regular expressions, and MySQL integration.

PHP's behavior can be configured at a variety of levels:

Global Configuration

The php.ini file is PHP's configuration fi le, containing more than 200 directives capable of tweaking nearly every aspect of the language's behavior. This fi le is parsed every time PHP is invoked, which for the server module version occurs only when the web server starts, and every time for the CGI version.

Host- and Directory-specific Configuration

If you lack access to the php.ini fi le, you may be able to change desired directives within Apache's httpd.conf or .htaccess files. For instance, to force the display of all PHP errors for solely your development domain (for instance http://dev.wjgilmore.com), add the following to a .htaccess file:

1
php_fl ag display_errors on

Hot Tip

Each directive is assigned one of three permission levels (PHP_INI_ALL, PHP_INI_PER_DIR, PHP_ INI_SYSTEM) which determines where it can be set. Be sure to consult the PHP documentation before tweaking settings outside of the php.ini fi le. See http://www.php.net/ini for a complete list of directives.

Script-specific Configuration Occasionally you'll want to tweak directives on a per-script basis. For instance to change PHP's maximum allowable execution time for a script tasked with uploading large fi les, you could call the ini_set() function from within your PHP script like so:

1
1
ini_set('max_execution_time', 60);

Changing the PHP File Extension

PHP's default fi le extension is .php, however you can change it to whatever you please by adding the desired extension to the AddType directive within Apache's httpd.conf fi le. For instance to configure Apache to recognize .dzone as a supported PHP file extension:

1
1
AddType application/x-httpd-php .php .dzone
Section 2

Popular Pear Packages

The PHP Extension Application Repository (PEAR) is the de facto service for distributing reusable PHP components. Over 500 packages are available for download from http://pear.php.net/, including these popular solutions:

PEAR Packages Description
Auth Facilitates authentication against IMAP, LDAP, plaintext files, most modern databases, RADIUS, and other authentication solutions.
Config Aids in the management of application confi guration data
HTML_QuickForm2 Streamlines the creation, processing, and validation of HTML forms.
HTML_Table Simplifi es the generation of dynamic HTML tables
HTTP_Upload Assists in the management of fi les uploaded through an HTML form.
Mail Facilitates transmission of e-mail through a website by supporting multiple mailer backends (including PHP's native mail() function, Sendmail, and SMTP)
MDB2 A database abstraction layer supporting numerous databases, including MySQL, PostgreSQL, Oracle, and MS SQL.
Net_UserAgent_ Detect Provides information regarding the user's browser and operating system.
PHPDocumentor Automates the code documentation creation and management process
PHPUnit Aids in the creation, execution and analysis of application tests
XML_RPC Supports creation of PHP-driven XML-RPC clients and servers.
Section 3

Popular Frameworks

Web frameworks help the programmer to embrace best practices, simultaneously decreasing errors and eliminating redundant code. If you haven't yet settled upon a framework, consider checking out one or several of the following popular solutions:

Framework Source
CakePHP http://www.cakephp.org/
CodeIgniter http://www.codeigniter.com/
eZ Components http://ez.no/ezcomponents
Prado http://www.pradosoft.com/
symfony http://www.symfony-project.org/
Zend Framework http://framework.zend.com/
Section 4

Object-Oriented PHP

Creating a Class

A class defines the behavior and characteristics of an entity you'd like to represent in an application. A sample class follows:

14
1
class RadioStation {
2
private $_id;
3
private $_name;
4
private $_frequency;
5
private $_band;
6
private $_audioStream;
7
public function setBand($band) {
8
$this->_band = $band;
9
}
10
public function getBand() {
11
return $this->_band;
12
}
13
...
14
}

Object Instantiation

To create an instance of a class (known as an object), you call the class name like you would a function, preceding it with the new keyword:

1
1
$wtvn = new RadioStation();

Class Constructors

Constructors are useful for performing initialization tasks at class instantiation time, thereby saving you the hassle of calling additional class methods. Constructors are declared using the __construct() method, like so:

6
1
function __construct($id="") {
2
// If specifi c station ID is requested, retrieve it
3
from the database
4
if (isset($id))
5
$this->fi nd($id);
6
}

Class Destructors

Custom class destructors can perform tasks when the object is destroyed. You can create a destructor using the __destruct() method:

4
1
function __destruct() {
2
printf("The radio station %s has been destroyed!",
3
$this->name);
4
}

Attribute and Method Visibility

PHP supports three levels of attribute and method visibility:

Attribute and Method Visibility Description
Public Public attributes and methods can be accessed anywhere
Private Private attributes and methods are only accessible within the class that defines them
Protected Protected attributes and methods are available to the class and its subclasses.

Class Constants

Class constants are defi ned with the const keyword, and can be referenced through the scope resolution operator (::). For instance, to define a constant identifying the RadioStation class' minimum supported PHP version:

1
1
const MIN_PHP_VER = '5.3';

You can then reference it outside the class like so:

1
1
echo RadioStation::MIN_PHP_VER;

Extending Classes

Class hierarchies can be created using the extends keyword. For instance, an application tasked with cataloging all major media outlets might first define a MediaOutlet class which defines some broad characteristics, and then child classes such as RadioStation and TVStation would inherit from it:

10
1
class MediaOutlet {
2
protected $owner;
3
protected $residentCountry;
4
public function setOwner($owner) {
5
...
6
}
7
}
8
class RadioStation extends MediaOutlet {
9
...
10
}

If you wanted to prevent child classes (in this case, RadioStation) from overriding a parent method, prefix it with the final keyword. For instance:

3
1
final public function setOwner($owner) {
2
...
3
}

Class Abstraction

The aforementioned MediaOutlet class would be more accurately defi ned as an abstract class, because it would never be explicitly instantiated (instead, one would instantiate derived classes such as RadioStation, TVStation, Newspaper, etc.). Abstract classes are declared using the abstract keyword:

3
1
abstract class MediaOutlet {
2
...
3
}

You can choose to override any methods found within an abstract class, which would then be inherited by its child classes, or alternatively you can declare them as abstract, requiring these methods be defined by any child.

Creating Interfaces

An interface helps developers rigorously enforce application specifications, and is similar to an abstract class, but contains solely the required method signatures. Any class implementing the interface must also implement all defined interface methods.

Interfaces are defined using the interface keyword and their names are typically prefixed with a capital I:

7
1
interface IRadioStation {
2
public function setBand($band);
3
public function getBand();
4
}
5
class RadioStation implements IRadioStation {
6
...
7
}
Section 5

Working with Arrays

The array is one of programming's most powerful data structures, capable of managing a seemingly endless variety of data.

Creating an Array

The following two examples all create an array named $stations consisting of three elements:

4
1
$stations = array (
2
"WTVN",
3
"WBNS",
4
"WYTS");

2
1
$stations = array();
2
$count = array_push($stations, "WTVN", "WBNS", "WYTS");

You can create an array consisting of a character- or numericallybased range using the range() function:

3
1
// $teenListenerDemographic =
2
// array(13,14,15,16,17,18,19)
3
$teenListenerDemographic = range(13,19);

Retrieving Array Contents

Indexed arrays such as those created so far can be accessed according to their numerical offset (beginning with a zerobased offset). For instance to retrieve the second value in the $stations array:

1
1
$callSignal = $stations[1];

Perhaps the most flexible way to enumerate array contents is through the foreach statement:

2
1
foreach($stations AS $station)
2
printf("%s<br />", $station);

Associative Arrays

Associative arrays give developers the opportunity to assign meaningful context to both the array value and its corresponding key:

5
1
$stations = array(
2
"WTVN" => "610",
3
"WBNS" => "1460",
4
"WYTS" => "1230 "
5
);

You can then obtain a value (in this case the station/band) by referencing its call signal:

2
1
// $channel = "610"
2
$channel = $stations["WTVN"];

The foreach statement proves equally useful for navigating associative arrays:

2
1
foreach($stations AS $key => value)
2
printf("%s => %s<br />", $key, $value);

Multidimensional Arrays

Multidimensional arrays are useful for representing more complex data structures:

9
1
$stations = array(
2
"AM" =>
3
array("WTVN" => "610",
4
"WBNS" => "1460",
5
"WYTS" => "1230"),
6
"FM" =>
7
array("WLVQ" => "96.3",
8
"WNCI" => "97.9")
9
);

Referencing an element isn't unlike the methods used for indexed and associative arrays; it's just a tad more verbose:

1
1
$channel = $stations["FM"]["WTVN"];

Determining Array Size

The number of elements found in an array can be determined using the count() function:

3
1
// Outputs "3 stations are being tracked"
2
printf("%d stations are being tracked",
3
count($stations));

Sorting Arrays

PHP offers a powerful assortment of functions (more than 70) capable of sorting arrays in a variety of ways. Most of these functions accept an optional parameter which can change the sorting behavior. Four values are supported, including SORT_ REGULAR for comparing elements without implicit typecasting, SORT_NUMERIC for comparing elements numerically, SORT_STRING for comparing elements as strings, and SORT_LOCALE_STRING, for sorting elements according to the defined locale.

Description Function
Sort an array while maintaining the key association bool asort(array &$array [, int $sort_fl ags])
Reverse sort an associative array while maintaining key association bool arsort(array &$array [, int $sort_fl ags])
Sort an associative array by key, maintaining index association bool ksort(array &$array [, int $sort_fl ags])
Reverse sort an associative array by key, maintaining index association bool krsort(array &$array [, int $sort_fl ags])
Sort an array case-insensitively in an order logically presumed by humans bool natcasesort($array &array)
Sort an array in an order logically presumed by humans bool natsort(array &$array)
Sort an array in reverse order bool rsort(array &$array [, int $sort_fl ags])
Sort an array according to the specifi cations of a user-defined function bool usort(array &$array, callback $comparison_function)
Sort an array according to the specifi cations of a user-defined function, maintaining index association bool uasort(array &$array, callback $comparison_function)
Key sort an array according to the specifi cations of a user-defined function bool uksort(array &$array, callback $comparison_function)

Consult the PHP manual for a complete listing: http://www.php.net/array.

Section 6

String Parsing

PHP supports over 100 functions identified as specific to string parsing and manipulation. Following are the most commonly used tasks.

Description Function
Converting an array to a string
3
1
$stations = array("WTVN","WBNS","WYTS");
2
$stations = implode(",", $stations)
3
// $stations = "WTVN,WBNS,WYTS"

Converting a string to an array
4
1
$stations = "WTVN,WBNS,WYTS";
2
$stations = explode(",", $stations);
3
// $stations[0]="WTVN", $stations[1]="WBNS",
4
$stations[2]="WYTS"

Counting words in a string
4
1
$sentence = "Columbus is home to numerous
2
radio stations";
3
$words = str_word_count($sentence);
4
// $words = 7

See also: count_chars()

Converting a string to uppercase
2
1
$callsign = strtoupper("wtvn");
2
// $callsign = "WTVN"

See also: lcwords(), strtolower(), ucfirst(), ucwords()
Strip HTML and PHP tags from a string
4
1
$input = "You won the <a href="http://www.
2
example.com">lottery!</a>."
3
$clean = strip_tags($input);
4
// $clean = "You won the lottery!"

See also: htmlentities(), htmlspecialchars()
Replace all occurrences of a substring
3
1
$phrase = "Big rockers listen to rock radio";
2
$phrase = str_replace("rock", "talk", $phrase);
3
// $phrase = "Big talkers listen to talk radio"

See also: substr_replace(), strireplace(), strtr()
Return part of a string as specifi ed by an offset
2
1
$description = "WFAN: Sports Radio 66";
2
$callsign = substr($description, 0, 4);

See also: strrchr()

Compare two strings case-insensitively
3
1
if (strcasecmp("WTVN", "wtvn") == 0)
2
echo "The strings are equal in a caseinsensitive
3
context."

See also: strncasecmp()

Convert newline characters to the HTML
tag
4
1
$stations = "WTVN: 610\nWLW: 700\nWYTS: 1230";
2
$html = nl2br($stations);
3
// $html = "WTVN: 610<br />WLW: 700<br />WYTS:
4
1230"

See also: htmlentities(), htmlspecialchars()

Section 7

Regular Expressions

PHP's regular expression features borrow heavily from both the Perl and POSIX formats, and in fact are formally identified as such.

Perl-compatible (PCRE) Regular Expression Functions

PHP supports eight PCRE-specific functions, including these commonly used solutions:

Function Description
array preg_grep(str $pattern, array $subject [, int $flags]) Searches $subject for $pattern, returning an array of matches. The optional $flags parameter can be set to PREG_GREP_INVERT, causing an array consisting of unmatched elements to be returned.
int preg_match(str $pattern, str $subject [, array &$matches [, int $flags [, int $offset]]]) Determines whether $pattern exists in $subject. If $matches is defi ned, a similarly named variable will be returned containing the matches. If $flags is set to PREG_OFFSET_CAPTURE, the string offset value will also be returned for each match. See preg_match_all() for a variation of this function.
mixed preg_ replace(mixed $pattern, mixed $replacement, mixed $subject [, int $limit [, int &$count]]) Searches $subject for $pattern, replacing any instances with $replacement. See preg_replace_ callback() for a variation of this function.

Common PCRE Pattern Modifiers

Modifi er Description
g Perform a global search
i Perform a case-insensitive search
m Treat the string as multiple lines (
s Ignore newline characters
x Ignore white space and comments
u Stop at the first match (ungreedy search)

Metacharacters

\A Match only beginning of string
\b Match a word boundary
\B Match anything but word boundary
\d Match a digit character
\D Match a non-digit character
\s Match a whitespace character
\S Match a non-whitespace character
[] Enclose a character class
() Enclose a character grouping or defi ne backreference
$ Match end of line
^ Match beginning of line
. Match any character except for newline
\ Quote the next metacharacter
\w Match any string containing underscore and alphanumeric characters
\W Match a string containing anything but underscore and alphanumericl characters

POSIX Regular Expression Functions

PHP supports seven functions as defi ned by the POSIX 1003.2 specifi cation, including these commonly used solutions:

int ereg(str $pattern, str $string [, array &$regs]) Search $string for a $pattern. You can optionally include the $regs parameter, which will cause an array of the same name to be returned containing each match. See eregi() for caseinsensitive counterpart.
string ereg_replace(str $pattern, str $replacement, str $string) Replace any patterns found in string with replacement. See eregi_replace() for caseinsensitive counterpart.
array split(str $pattern, str $string [, int $limit]) Split $string into an array, dividing it according to $pattern. See spliti() for case-insensitive counterpart.

POSIX Regular Expression Syntax

[0-9] Any decimal digit from 0 - 9
[a-z] Any character from lowercase a through lowercase z
[A-Z] Any character from uppercase A through uppercase Z
[A-Za-z] Any character from upper case A through lowercase z
p+ Any string containing at least one p
p* Any string containing zero or more p's
p? Any string containing zero or one p
p{N} Any string containing sequence of two p's
p{N,M} Any string containing sequence of between N and M p's
p{2,} Any string containing sequence of at least two p's
p$ Any string with p at the end of it
^p Any string with p at the beginning of it
[^a-zA-Z] Any string not containing characters a-z through A-Z
p.p Any string containing p followed by any character, followed by another p

Regular Expression Examples

Validating a Phone Number

Presumes the required format is XXX-XXX-XXXX.

8
1
// PCRE
2
if (preg_match('/^[2-9]{1}\d{2}-\d{3}-\d{4}$/', '614-
3
599-2599'))
4
echo "Valid number!";
5
// POSIX
6
if (ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', '614-
7
999-2599'))
8
echo "Valid number!";

Validating a Username

Presumes username is between 6 and 10 alphabetical and numerical characters.

6
1
// PCRE
2
if (preg_match('/^[a-z0-9]{6,10}$/i', '800gilmore'))
3
echo "Valid username!";
4
// POSIX
5
if (eregi('^[a-z0-9]{6,10}$', '800gilmore'))
6
echo "Valid username!";

Turn URLs into Hyperlinks

10
1
// PCRE
2
$text = "Go to http://www.wjgilmore.com.";
3
$html = preg_replace('/\s(\w+:\/\/)(\S+\.?)(\w+)/',
4
' <a href="\\1\\2\\3">\\1\\2\\3</a>', $text);
5
// POSIX
6
$text = "Go to http://www.wjgilmore.com. ";
7
$html= ereg_replace('[a-zA-Z]+://(([.]?[a-zAZ0-
8
9_/-])*)', '<a href="\\0">\\0</a>', $string);
9
// $html = "Go to <a href=" http://www.wjgilmore.
10
com">http://www.wjgilmore.com."
Section 8

Telling Time with PHP

The Date Function

The date() function is perhaps one of PHP's most commonly used functions, capable of retrieving nearly every temporal attribute of a specific timestamp.

1
1
string date(string $format [, $int $timestamp])
a Lowercase Ante meridiem and Post meridiem
A Uppercase Ante meridiem and Post meridiem
B Swatch Internet Time
c ISO 8601 date
e Timezone identifi er
g 12-hour hour format without leading zeros
G 24-hour hour format with leading zeros
h 12-hour hour format with leading zeros
H 24-hour hour format with leading zeros
i Minutes with leading zeros
I Specifi es whether date is in daylight savings time
O Difference to Greenwich time (GMT) in hours
P Difference to Greenwhich time (GMT) with colon between hours and minutes
r RFC 2822 date
s Seconds, with leading zeros
T Timezone abbreviation
u Milliseconds
U Seconds since Unix Epoch
z Timezone offset in seconds

Day Parameters

d Day of month, two digits with leading zeros
D Three letter textual representation of day
j Day of month without leading zeros
l Textual representation of day
N ISO-8601 numeric representation
S Two character English ordinal suffi x for day of month
w Numeric representation of day of week
z Numerical offset of day of year

Week Parameters

W ISO-8601 week number of year

Month Parameters

F Full text representation of month
m Numeric representation of month
M Three letter textual representation of month
n Numeric representation of month, without leading zeros
t Number of days in given month

Year Parameters

L Whether date is a leap year
o ISO-8601 year number
Y Full numeric representation of year
y Two digit representation of year

Date Function Examples

July 29, 2008 print date('F j, Y');
7/29/08 print date('m/j/y');
Today is Tuesday, July 29 10:45:21am printf("Today is %s", date('l, F j h:i:sa'));
There are 31 days in July. printf("There are %d days in %s.", date('t'), date('F'));

Setting the Timezone

You can set the timezone for all scripts by setting the date. timezone configuration directive within the php.ini file, or on a per-script basis using the date_default_timezone_set() function.

Other Useful Functions

Function Description
int mktime([int $hour [, int $min [, int $sec [, int $month [, int $day [, int $year [, int $is_dst]]]]]]]) Returns the Unix timestamp for a given date
int time() Returns current timestamp
string setlocale(int $category, string $locale) Sets the script locale
int strtotime(string $time [, int $now]) Converts English textual date/time description into a Unix timestamp
bool checkdate(int $month, int $day, int $year) Validates the date composed by the $month, $day, and $year arguments.
array getdate([int $timestamp]) Retrieves a timestamp as an associative array. Associative keys include seconds, minutes, hours, mday (day of the month), wday (day of week), mon (month), year, yday (day of the year), weekday, month, and 0 (seconds since UNIX Epoch)

PHP 5.1.0 introduced an object-oriented DateTime class. See http://www.php.net/DateTime for more information.

Date-related Examples

Output "December 25 falls on a Thursday" $date = date('l', mktime(0,0,0,12,25,2008)); printf("December 25 falls on a %s", $date);
Output "Next month is August." printf("Next month is %s", date('F', strtotime('+1 month')));
Output "Last Friday fell on July 25, 2008" $date = date('F d, Y', strtotime('Last Friday')); printf("Last Friday fell on %s", $date);
Output "Oggi ' marted'" setlocale(LC_ALL, "it_IT");
printf("Oggi è %s", strftime("%A"));
Retrieve a page's lastmodifi ed date echo date('l, F j h:i:sa', fi lemtime($_SERVER["SCRIPT_ NAME"]));
Calculate the difference between two dates $date1 = strtotime("2008-08-14");
$date2 = strtotime("2008-07-11");
$diff = $date2 - $date1;
printf("Difference in days: %s", $diff / 60 / 60 / 24);
Section 9

MySQL Integration

Although PHP supports several popular databases, MySQL remains by far the most common database solution. PHP's MySQL support has evolved considerably in recent years, with the MySQLi (MySQL Improved) extension being the current recommended solution. Here are the most commonly used methods.

Hot Tip

The PHP 5.3 release includes a new MySQL driver known as mysqlnd (MySQL Native Driver). This driver eliminates the need for a previously required special licensing exception (FLOSS), and eliminates the need to have MySQL installed on the same machine as PHP. It has already been integrated with the mysql and mysqli extensions, with PDO support in the works.

Connecting to MySQL

The mysqli extension provides a number of ways to connect to MySQL, but the easiest involves just passing the connection data along when instantiating the mysqli class:

6
1
mysqli new mysqli([string host [, string user [, string
2
pswd
3
[string dbname [int port [string socket]]]]]]);
4
Here's an example:
5
$mysqli = new mysqli("localhost", "webuser", "secret",
6
"corporate");

Handling Connection Errors

In case of connection error you can retrieve both the error number and error string using the errno() and error() methods. Example:

4
1
if ($mysqli->errno) {
2
printf("Unable to connect: %s", $mysqli->error);
3
exit();
4
}

Sending a Query to the Database

Once the connection has been established, you can begin querying the database. Queries are sent using the query() method:

1
1
mixed query(string $query [, int $resultmode])

Setting the optional $resultmode parameter to MYSQLI_USE_ RESULT will cause query() to return the result as an unbuffered set.

Example:

2
1
$result = $mysqli->query("SELECT callsign FROM
2
stations");

Sending INSERT, UPDATE, and DELETE queries works identically. For instance, sending an UPDATE query works like this:

2
1
$result = $mysqli->query("UPDATE stations SET station
2
= '610' WHERE callsign = 'WTVN'");

Retrieving Data

Data can be parsed from the result set using a number of data structures, including via associative and indexed arrays, and objects.

Retrieving data as an associative array:

3
1
while ($row = $result->fetch_array(MYSQLI_ASSOC) {
2
printf("%S", $row["callsign"]);
3
}

Retrieving data as an indexed array:

3
1
while ($row = $result->fetch_row() {
2
printf("%S", $row[0]);
3
}

Retrieving data as an object:

3
1
while ($row = $result->fetch_object() {
2
printf("%S", $row->callsign);
3
}

Determining the Number of Rows Affected and Retrieved

To determine the number of affected rows after sending an INSERT, UPDATE, or DELETE query, use the affected_rows property.

Example:

3
1
$result = $mysqli->query("UPDATE stations SET station =
2
'610' WHERE callsign = 'WTVN'");
3
printf("Rows affected: %d", $result->rows_affected);

To determine how many rows were returned when using a SELECT query, use the num_rows property:

3
1
$result = $mysqli->query("SELECT * FROM stations WHERE
2
state ='Ohio');
3
printf("Rows affected: %d", $result->num_rows);

Working with Prepared Statements

Prepared statements both optimize query performance and decrease the possibility of SQL injection attacks by separating the query data from the logic, fi rst passing the query to MySQL for preparation, binding variables to the query columns, and fi nally passing the data to MySQL for query execution.

To prepare a query, create the query, and then initialize a statement object using the stmt_init() method:

2
1
$query = "INSERT INTO stations VALUES(?, ?)";
2
$stmt = $mysqli->stmt_init();

Next the query is prepared by passing it to MySQL using the prepare() method:

1
1
$stmt->prepare($query);

Next, bind the parameters using the bind_param() method:

1
1
$stmt->bind_param('ss', "WTVN", "610");

Finally, execute the prepared statement using the execute() method:

1
1
$stmt->execute();

You can also use prepared statements to retrieve results. The general process used to execute the previous INSERT query is identical to that required for executing a SELECT query, except that the bind_param() method is not required, and you bind results following a call to the execute() method. An example follows:

8
1
$query = "SELECT callsign, frequency FROM stations
2
ORDER BY callsign";
3
$stmt = $mysqli->stmt_init();
4
$stmt->prepare($query);
5
$stmt->execute();
6
$stmt->bind_result($callsign, $frequency);
7
while ($stmt->fetch())
8
printf("%s: %s<br />", $callsign, $frequency);

Transactions

By default the MySQLi extension will render each query "permanent" upon successful execution, actually changing the database's contents when INSERT, UPDATE, and DELETE queries are processed. However the success of some tasks depend upon the successful execution of several queries, and until all have occur. ATM transactions and online credit card processing are common examples requiring several queries. Using transactions, you can change the MySQLi extension's behavior, committing a series of queries as you see fit.

To begin a transaction, start by disabling the autocommit feature:

1
1
$mysqli->autocommit(FALSE);

Execute the various queries as you see fit, and if everything proceeds as you expect, execute the commit() method:

1
1
$mysqli->commit();

Otherwise, if a problem occurs, execute the rollback() method:

1
1
$mysqli->rollback();
Section 10

Useful Online Resources

Resource Source
PHP Zone http://php.dzone.com
The PHP Website http://www.php.net
Zend Developer Zone http://devzone.zend.com/
PlanetPHP http://www.planet-php.net/
PHPDeveloper.org http://phpdeveloper.org/
Developer.com http://www.developer.com/
ONLamp PHP Devcenter http://www.onlamp.com/php/

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Applying Hexagonal Architecture to a Symfony Project
related article thumbnail

DZone Article

Implementing Domain-Driven Design in PHP
related article thumbnail

DZone Article

How to Convert XLS to XLSX in Java
related article thumbnail

DZone Article

Automatic Code Transformation With OpenRewrite
related refcard thumbnail

Free DZone Refcard

Getting Started With Low-Code Development
related refcard thumbnail

Free DZone Refcard

JavaScript Test Automation Frameworks
related refcard thumbnail

Free DZone Refcard

Salesforce Application Design
related refcard thumbnail

Free DZone Refcard

E-Commerce Development Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: