Tải bản đầy đủ (.pdf) (30 trang)

Beginning PHP6, Apache, MySQL Web Development- P25 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (377.98 KB, 30 trang )

Appendix C: PHP6 Functions
751
Miscellaneous Functions
Function signatures marked with a * are not available when running on Windows.
Function Description

void __halt_compiler(void) Halt the execution of the PHP compiler.

int connection_aborted(void) Return whether the client connection has been
aborted.

int connection_status(void) Return the connection status.

mixed constant(string $name) Return the value of a constant.

bool define(string $name, mixed
$value[, bool $case_insensitive])

Define a constant.

bool defined(string $name) Return whether a constant exists.

void die([mixed $status]) Alias for exit() .

mixed eval(string $string) Evaluate a string as PHP code.

void exit([mixed $status]) Terminate execution of the script.

mixed get_browser([string $user_
agent[, bool $return_array])


Return an object with information about a browser.
Information will be returned as an array if
$return_array is true. Relies on browscap.ini .

mixed highlight_file(string
$filename[, bool $return])

Output the syntax - highlighted source PHP file. The
source will be returned as a string instead if
$return is true.

mixed highlight_string(string
$string[, bool $return])

Output a syntax - highlighted string of PHP code.
The string will be returned instead if
$return is
true.

int ignore_user_abort([bool
$value])

Set whether a script should continue executing
after the user aborts the connection.

string php_strip_
whitespace(string $filename)

Return the source code of a file with comments and
whitespace removed.


mixed show_source(string
$filename)

Alias for
highlight_file() .

int sleep(int $seconds) Pause execution of the script for a specified number
of seconds.
bapp03.indd 751bapp03.indd 751 12/10/08 5:34:05 PM12/10/08 5:34:05 PM
Appendix C: PHP6 Functions
752
Function Description

array sys_getloadavg(void) * Return an array with the system ’ s load averages
over the last 1, 5, and 15 minutes.

mixed time_nanosleep(int
$seconds, int $nanoseconds)
*
Pause execution of the script for a specified number
of seconds and nanoseconds.

bool time_sleep_until(float
$timestamp)
*
Pause execution of the script until a specified time.

string uniqid($prefix[, bool
$entropy])


Return a unique ID based on the current time and
named prefix.

void usleep(int $microseconds) Pause execution of the script for a specified number
of microseconds.
bapp03.indd 752bapp03.indd 752 12/10/08 5:34:06 PM12/10/08 5:34:06 PM
D
MySQL Data Types
This appendix contains a listing of data types that are available in MySQL. Visit http://
dev.mysql.com/doc/refman/5.1/en/data - type - overview.html
for a complete discussion
on each data type.
Numeric Data Types
MySQL Field Type Description

BIGINT[(m)] [UNSIGNED]
Numeric field that stores integers from Ϫ 9,223,372,
036,854,775,808 to 9,223,372,036,854,775,807.
m
represents the maximum display width. Adding the

UNSIGNED parameter allows storage of 0 to
18,446,744,073,709,551,615.

BIT[(m)] Bit - type field. m represents the optional number of
bits per value.

BOOL, BOOLEAN Synonym for TINYINT(1) . A value of 0 represents
false, and nonzero values represent true.


DEC Synonym for DECIMAL .

DECIMAL[(m[,d])] [UNSIGNED] A fixed - point numeric field that can store decimals.

m represents the total number of displayed digits. d
represents how many digits follow the decimal
point.
UNSIGNED allows only positive numbers to be
stored.
bapp04.indd 753bapp04.indd 753 12/10/08 5:33:08 PM12/10/08 5:33:08 PM
Appendix D: MySQL Data Types
754
MySQL Field Type Description

DOUBLE[(m,d)] [UNSIGNED] A double - precision floating - point number that stores
values from Ϫ 1.7976931348623157E+308 to
Ϫ 2.2250738585072014E Ϫ 308, 0, and
2.2250738585072014E Ϫ 308 to 1.7976931348623157E+308.
m represents the total number of displayed digits. d
represents how many digits follow the decimal point.

UNSIGNED allows only positive numbers to be stored.

DOUBLE PRECISION[(m,d)]
[UNSIGNED]

Synonym for
DOUBLE .


FIXED Synonym for DECIMAL .

FLOAT[(m,d)] [UNSIGNED] A single - precision floating - point number that stores values
from Ϫ 3.402823466E+38 to Ϫ 1.175494351E Ϫ 38, 0, and
1.175494351E Ϫ 38 to 3.402823466E+38.
m represents the
total number of displayed digits.
d represents how many
digits follow the decimal point.
UNSIGNED allows only
positive numbers to be stored.

INT[(m)] [UNSIGNED]
Numeric field that stores integers from Ϫ 2,147,483,648 to
2,147,483,647.
m represents the maximum display width.
Adding the
UNSIGNED parameter allows storage of 0 to
4,294,967,295.

INTEGER[(m)] [UNSIGNED] Synonym for INT .

MEDIUMINT[(m)] [UNSIGNED]
Numeric field that stores integers from Ϫ 8,388,608 to
8,388,607.
m represents the maximum display width.
Adding the
UNSIGNED parameter allows storage of 0 to
16,777,215.


NUMERIC Synonym for DECIMAL .

SMALLINT[(m)] [UNSIGNED]
Numeric field that stores integers from Ϫ 32,768 to 32,767. m
represents the maximum display width. Adding the

UNSIGNED parameter allows storage of 0 to 65,535.

REAL[(m,d)] [UNSIGNED] Synonym for DOUBLE . (Note: If REAL_AS_FLOAT mode is
enabled, then
REAL is a synonym for FLOAT .)

TINYINT[(m)] [UNSIGNED]
Numeric field that stores integers from Ϫ 128 to 127.
m
represents the maximum display width. Adding the

UNSIGNED parameter allows storage of 0 to 255.
bapp04.indd 754bapp04.indd 754 12/10/08 5:33:08 PM12/10/08 5:33:08 PM
Appendix D: MySQL Data Types
755
Date and Time Data Types
MySQL Field Type Description

DATE Stores a date as YYYY - MM - DD from 1000 - 01 - 01 to 9999 - 12 - 31.

DATETIME Stores both a date and time as YYYY - MM - DD HH:MM:SS from 1000 - 01 - 01
00:00:00 to 9999 - 12 - 31 23:59:59.

TIMESTAMP Stores a UNIX Epoch timestamp as YYYY - MM - DD HH:MM:SS from

1970 - 01 - 01 00:00:01 to 2038 - 01 - 09 03:14:07.

TIME
Stores a time as HH:MM:SS from Ϫ 838:59:59 to 838:59:59.

YEAR[(2|4)] Stores a year as either YY or YYYY , depending on whether two - or four -
digit format is specified (default is four - digit). The range is from 1901 to
2155 in four - digit format, and from 70 to 69, representing years from
1970 to 2069, in two - digit format.
String Data Types
MySQL Field Type Description

BINARY[(m)] Stores fixed - length binary byte strings. m represents
the length in bits.

BLOB[(m)] Stores binary byte strings. m represents the length
in bytes from 0 to 65,535.

[NATIONAL] CHAR[(m)] Synonym for CHARACTER .

CHAR BYTE[(m)] Synonym for BINARY .

[NATIONAL] CHARACTER[(m)] Stores a fixed - length character string that is right -
padded with spaces.
m represents the length in
characters from 0 to 255.

[NATIONAL] CHARACTER VARYING[(m)] Stores a variable - length character string. m
represents the length in characters from 0 to 65,535.


ENUM( ‘ value1 ’ , ‘ value2 ’ , ) Stores a string value. Allows only specified values
to be stored in the field (up to a maximum of 65,535
different values).

LONGBLOB Stores binary byte strings. m represents the length
in bytes from 0 to 4,294,967,295 (4GB).
bapp04.indd 755bapp04.indd 755 12/10/08 5:33:09 PM12/10/08 5:33:09 PM
Appendix D: MySQL Data Types
756
MySQL Field Type Description

LONGTEXT Stores a variable - length character string. m
represents the length in characters from 0 to
4,294,967,295 (4GB).

MEDIUMBLOB Stores binary byte strings. m represents the length
in bytes from 0 to 16,777,215.

MEDIUMTEXT Stores a variable - length character string. m
represents the length in characters from 0 to
16,777,215.

NCHAR[(m)] Synonym for NATIONAL CHARACTER .

NVCHAR[(m)] Synonym for NATIONAL CHARACTER VARYING .

SET( ‘ value1 ’ , ‘ value2 ’ , ) Stores a set of string values from the specified list
values (up to a maximum of 64 members).

TEXT[(m)] Stores a variable - length character string. m

represents the length in characters from 0 to 65,535.

TINYBLOB Stores binary byte strings. m represents the length
in bytes from 0 to 255.

TINYTEXT Stores a variable - length character string. m
represents the length in characters from 0 to 255.

VARBINARY[(m)] Stores variable - length binary byte strings. m
represents the length in bits.

[NATIONAL] VARCHAR[(m)] Synonym for CHARACTER VARYING .
Spatial Data Formats
Spatial data is beyond the scope of this book. See />supported - spatial - data - formats.html
for more information on the standard spatial formats used
by MySQL.
bapp04.indd 756bapp04.indd 756 12/10/08 5:33:09 PM12/10/08 5:33:09 PM
E
My SQL Quick Reference
This appendix lists some quick reference notes for your use. These topics are covered in more
depth in Chapter 3 and on the MySQL web site at
www.mysql.com .
Database Manipulation Commands
Use the following commands to create and make changes to your database and tables.
Command What It Does

CREATE DATABASE [IF NOT EXISTS]
db_name

Creates a database


CREATE TABLE [IF NOT EXISTS] tbl_
name (col1 col_type, col2 col_
type, )

Creates a table

ALTER TABLE tbl_name ADD col col_
type [AFTER col],

Adds a new column to a table in the database

ALTER TABLE tbl_name MODIFY col
new_col_type,

Changes columns ’ type definitions

ALTER TABLE tbl_name CHANGE old_
col new_col new_col_type,

Changes columns ’ names and type definitions

ALTER TABLE tbl_name DROP col, Removes columns from a table in the
database

RENAME TABLE old_tbl_name TO new_
tbl_name

Renames a table in the database
bapp05.indd 757bapp05.indd 757 12/10/08 5:31:50 PM12/10/08 5:31:50 PM

758
Appendix E: My SQL Quick Reference
Retrieving Data from the Database
You can access the data stored in your tables with the following statement:
SELECT col1[, col2, . . .] FROM tbl_name [WHERE condition] [ORDER BY col
[ASC|DESC]] [LIMIT offset, num_rows]

You can use * to retrieve all columns in a table:
SELECT * FROM tbl_name

Condition Clauses
Use the following conditions in conjunction with the SELECT statement:
col = value
col > value
col < value
col > = value
col < = value
col != value
col < > value
col BETWEEN value1 AND value2
col NOT BETWEEN value1 AND value2
col LIKE value
col NOT LIKE value
col IS NULL
col IS NOT NULL
col IN (value1, value2, value3, . . .)
col NOT IN (value1, value2, value3, . . .)

Command What It Does


INSERT [IGNORE] INTO tbl_name [(col1,
col2, … )] VALUES (value1, value2, )

Inserts a row into a table

UPDATE [IGNORE] tbl_name SET
col1=value1, col2=value2, WHERE
condition [ORDER BY ] [LIMIT count]

Modifies information already stored in the
table

DELETE [IGNORE] FROM tbl_name WHERE
condition [ORDER BY ] [LIMIT
count]

Deletes information from the table

TRUNCATE TABLE tbl_name Deletes all information from the table

DROP TABLE [IF EXISTS] tbl_name Deletes a table from the database

DROP DATABASE [IF EXISTS] db_name Deletes a database
bapp05.indd 758bapp05.indd 758 12/10/08 5:31:50 PM12/10/08 5:31:50 PM
759
Appendix E: My SQL Quick Reference
MySQL supports wildcard matching. Use to match a single character. Use % to match zero or more
characters.
Selecting from Multiple Tables
You can retrieve information from two or more tables at once by using JOIN s. MySQL supports the

following syntax variations:

SELECT
table1.col1, table1.col2, table2.col1, table2.col2
FROM
table1, table2
WHERE
table1.col1 = table2.col1

or
SELECT
table1.col1, table1.col2, table2.col1, table2.col2
FROM
table1 JOIN table2 ON table1.col1 = table2.col1

Sorting the Results
You can sort the results of the SELECT query by using the ORDER BY clause (and the optional ascending
or descending qualifier):

SELECT * FROM table WHERE col1 = value1 ORDER BY col2 [ASC|DESC]

Limiting the Results
If you would like to limit the results returned from your query, you can do so with a LIMIT clause:
SELECT * FROM table WHERE col1 = value1 LIMIT [offset,] row_count

bapp05.indd 759bapp05.indd 759 12/10/08 5:31:51 PM12/10/08 5:31:51 PM
bapp05.indd 760bapp05.indd 760 12/10/08 5:31:51 PM12/10/08 5:31:51 PM
F
Comparison of Text Editors
Many software programs are available that you can use to enter all your code. They each have

different features, some that you might view as better than others, depending on your needs and
personal preferences. We ’ ve put together the following chart to help you compare apples with
apples. It lists some of the more popular editors alphabetically and compares them against some
common text editor features.
Many of these editors provide similar features, so your decision really depends on your budget,
your needs, and how comfortable you are with each user interface.
You can read more about features not listed here, because many of these editors provide other
unique benefits. We encourage you to visit the following web sites to download these programs
and/or to get more information about them:
Dreamweaver CS3:
www.adobe.com/products/dreamweaver/
EditPlus:
www.editplus.com
Geany:
www.geany.org
HTML - Kit:
www.chami.com/html - kit/
jEdit:
www.jedit.org
Notepad:
www.microsoft.com
PhpED:
www.nusphere.com
PHPEdit:
www.waterproof.fr
TextPad:
www.textpad.com
UltraEdit - 32:
www.ultraedit.com
WordPad:

www.microsoft.com
Zend Studio:
www.zend.com












bapp06.indd 761bapp06.indd 761 12/10/08 5:30:08 PM12/10/08 5:30:08 PM
Appendix F: Comparison of Text Editors
762
Editor
Highlighted
Syntax
Spell
Checker
Built - in
FTP
Access
Line
Numbers
Word
Wrap

PHP Code
Auto -
Completion
WYSIWYG
Web
Design
Editor
Dreamweaver
CS3
✓ ✓ ✓ ✓ ✓ ✓ ✓
EditPlus
✓ ✓ ✓ ✓ ✓

Geany


✓ ✓ ✓

HTML - Kit
Tools
✓ ✓ ✓ ✓ ✓ ✓ ✓
jEdit


✓ ✓ ✓ ✓

Notepad


PhpED

✓ ✓ ✓ ✓ ✓ ✓

PHPEdit


✓ ✓ ✓ ✓

TextPad


✓ ✓

UltraEdit - 32
✓ ✓ ✓ ✓ ✓ ✓

WordPad


Zend Studio


✓ ✓ ✓ ✓

bapp06.indd 762bapp06.indd 762 12/10/08 5:30:09 PM12/10/08 5:30:09 PM
Appendix F: Comparison of Text Editors
763
Database
Connectivity
Content
Preview

Multiple
Undo/Redo
Search and
Replace
Code
Folding
PHP
Debugging
CVS/
Subversion
Integration Price
✓ ✓ ✓ ✓ ✓


$399

✓ ✓ ✓ ✓
$30

✓ ✓ ✓
F r e e

✓ ✓ ✓ ✓
$65

✓ ✓
F r e e


F r e e

✓ ✓ ✓ ✓ ✓ ✓ ✓
$299




✓ ✓
$90

✓ ✓
$33
✓ ✓ ✓ ✓ ✓
$49.95


F r e e
✓ ✓ ✓ ✓ ✓ ✓ ✓
$349
bapp06.indd 763bapp06.indd 763 12/10/08 5:30:10 PM12/10/08 5:30:10 PM
bapp06.indd 764bapp06.indd 764 12/10/08 5:30:11 PM12/10/08 5:30:11 PM
G
Choosing a Third - Party Host
Many people like to run their own servers out of their homes or offices, and that is a feasible
solution for hosting, if you have the time and network resources. But sometimes hosting your own
web site can lead to more problems than it ’ s worth. You need to think about backup power, keeping
security holes patched, performing regular maintenance and upgrades, and many other issues. And
keep in mind that not only do you need to have a web server running, but you also need to have
something to manage your domain records as well, a Domain Name System (DNS) server.
With third - party hosting solutions, you can have trained IT professionals who make sure your web
server stays up and running 24 hours a day, at an affordable price. It ’ s their job to make sure your

site is secure and always available for viewing.
Hosting Options
If you decide to have a third party host your site, you have many options to choose from when
making your hosting choice. Here are a few criteria to look at when you select a host:
Supported languages: PHP, JAVA, CGI, ASP
Supported databases: MySQL, PostgreSQL, MS SQL
Server control: super user (su) or root access
Server access: Such as FTP and SSH
Configuration ability: Web server settings/configurations, cron jobs,
.htaccess support
Administration GUIs: E - mail, database, user setup
Bandwidth usage: Web site, e - mail, streaming media, database connections
Price: Based on features, contract time, and other criteria








bapp07.indd 765bapp07.indd 765 12/10/08 5:29:02 PM12/10/08 5:29:02 PM
766
Appendix G: Choosing a Third - Party Host
Keep in mind that you aren ’ t likely to have every combination and possibility with every host, so it ’ s
important that you research your prospective hosts to make a well - thought - out decision before jumping
into a long - term contract. To that end, let ’ s get into a little more detail about each of these topics.
Supported Languages
Obviously, we ’ re assuming you want to use PHP (you did buy this book, after all), but there are other
languages you may need to use. There may be a time when another language, such as Perl, Python, or

even Java, is better suited for your needs than PHP. For example, perhaps you have to accomplish
something a client already has set up at a different host or server, using a different programming
language. It is nice to at least have the option of using the existing code, rather than spending the time
and money to redevelop the application in PHP.
Supported Databases
Again, because this book is geared toward MySQL, we assume you will probably be looking for a host
that supports MySQL. However, you can use many other databases with PHP. Here are just some of the
databases that PHP can work with:
MySQL
PostgreSQL
MS SQL Server
MS Access
Firebird
Sybase
PHP even comes with the embedded database SQLite enabled. Depending on your situation, you may
want to choose a host that has more than one of these databases set up by default. Some larger
companies, for example, are using MS SQL as their database, usually because they are using ASP.NET
for programming. Should you need to convert any site to PHP, you will be glad to know that PHP can
connect and work nicely with MS SQL as well.
Server Control and Access
Many hosts won ’ t give a web developer full access or control over their hosted domain. We tend to shy
away from those hosts, because you are more likely to run into problems with them when you want to
do some custom configuration to the server.
Look into the type of access your host provides. Obviously, your host will give you FTP access so you
can upload your files to the web server. Some hosts, however, will give you FTP access but nothing else.
The problem is that you are likely to run into a situation in which you want to configure your server. For
this, you will need SSH (Secure Shell) access to use the command line.
In fact, the ability to configure is often necessary when performing tasks that usually aren ’ t offered by
hosts by default. For example, consider
.htaccess files. With .htaccess files, you can deny and allow







bapp07.indd 766bapp07.indd 766 12/10/08 5:29:02 PM12/10/08 5:29:02 PM
767
Appendix G: Choosing a Third - Party Host
access to certain files and directories, based on the users you allow using htpasswd . (See Chapter 12 for
more information on
.htaccess and htpasswd .)
Along with
.htaccess , most hosts allow you to use cron jobs, but are not likely to set them up for you.
Therefore, you need to remote into the server and edit the
crontab file to enable you to run scheduled
tasks. There are countless configuration settings that you might want to change, if your host allows you
to configure them. Keep all this in mind when choosing your hosting solution.
Administration GUI s
Certain hosts offer a dministration graphical user interfaces, (GUIs) or user control panels, as a feature of
their packages. A lot of people don ’ t really care for GUIs, but when you don ’ t have a choice — either
because you don ’ t have sufficient access to the server or you don ’ t fully understand how to get things
done at a command prompt — a point - and - click solution can be a wonderful tool.
The interface can be as simple as one that allows you to view information about the server, or it can be as
complex as one that allows you to install applications and programming languages with the click of a
button. Also, keep in mind that many control panels have utilities that allow clients to administer their
own e - mail users. With such a feature, the client can simply log on to the control panel and set up and
delete users as the need arises, rather than having to call you or the hosting company to set up an e - mail
account.
Bandwidth and Site Usage

Bandwidth and site usage both can factor into the overall price of hosting. Hosting companies usually
give out only so much bandwidth usage per site per month. There is usually a hefty charge if you go
over that amount. Consider the following issues when looking into bandwidth:
Web site traffic
E - mail usage and storage
Database connections
Streaming media
If you have heavy activity in any or all of these areas, you might get billed for bandwidth overutilization
before you know it. You need to consider how many people will visit your site on average. In addition,
some hosts count e - mail usage in the end - of - the - month calculation used to tally your bill. Some hosts
will even go so far as to monitor your FTP access and count that toward the total bandwidth used.
Database connections don ’ t really relate to bandwidth usage, but hosts often limit the number of
database connections you can make, as another way to control the number of people allowed to visit the
site at one time.
Finally, streaming media is very heavy on bandwidth; should you plan to use it as a form of conveying
information to the end users of your site, then your hosting bill could rise dramatically.




bapp07.indd 767bapp07.indd 767 12/10/08 5:29:03 PM12/10/08 5:29:03 PM
768
Appendix G: Choosing a Third - Party Host
Pricing
You need to consider all the areas discussed so far when figuring out how much your host is worth to
you. Look at the price per feature rather than the total price. You won ’ t often get all the features you
want for your site, but as long as you get most of them and you choose the host that has the lowest price
per feature, then you will probably make a wise hosting choice.
Ask yourself how much a particular feature is worth to you, when using price to make your choice.
Remember that some hosting companies require that you sign up for a full year and won ’ t offer a refund

if you decide the service isn ’ t worth the money you are paying. You want to find a host that will allow
you to choose either monthly, quarterly, or yearly hosting options. That way you don ’ t have to wait a full
year to leave if you ’ re dissatisfied. Just keep in mind that when you choose a shorter option, such as
monthly or quarterly, the host will often charge a little more than if you pay up front, or they may charge
service setup fees that might be waived if you paid up front.
Making the Choice
When making your hosting decision, it ’ s very important to consider the criteria outlined in this
appendix. You really don ’ t want to get stuck in a situation in which you are unhappy with the service
you are receiving, or, worse yet, in which your paying client is disappointed with services you
recommended.
The following is a list of 12 hosting options that we feel offer the best bang for your buck. You may want
to consider them when making your decision:

www.olm.net

www.lunarpages.com

www.jumpline.com

www.startlogic.com

www.ipowerweb.com

www.midphase.com

www.infinology.com

www.powweb.com

www.invision.net


www.ait.com

www.1and1.com

www.websitesource.com












bapp07.indd 768bapp07.indd 768 12/10/08 5:29:03 PM12/10/08 5:29:03 PM
H
An Introduction to
PHP Data Objects
PHP is a terrific programming language. It is relatively easy to learn, especially if you are already
familiar with other programming languages. You can build some excellent interactive web pages
that access databases, authenticate users, and provide dynamic, up - to - date content for your
visitors in no time at all.
So, let ’ s say you just finished creating your company ’ s web site. It ’ s perfect — users are being
served up - to - the - minute content, and you have set up a complex content management system
(CMS) that enables designated employees in the company to create new content. It ’ s efficient, it ’ s
pretty, and you feel pretty darned good about it.

As you sit here thumbing through these final pages of the book and wondering what final nuggets
of useful information we can share with you, we present you with a scenario: You have just
finished a tough assignment assigned to you by your IT manager. She congratulates you on a job
well done and engages you in general chit - chat — you know, the usual. As she gets up to leave,
she stops in the doorway and casually mentions something that is about to completely overload
your work schedule. . .
“ Oh, by the way, the accounting department is switching to an Ingres database to support their
accounting software. It ’ s pretty slick. And since we ’ ll be using Ingres in accounting, we ’ ve decided
all of our databases should be standardized on Ingres throughout the rest of the company, for
conformance. That ’ s not going to be a problem, is it? ”
Every developer has had something like this happen at one point or another, so you are not alone.
One of the wonderful things about PHP is that it supports a very wide variety of different
databases:
dBase
DB++
FrontBase



bapp08.indd 769bapp08.indd 769 12/10/08 5:28:16 PM12/10/08 5:28:16 PM
770
Appendix H: An Introduction to PHP Data Objects
filePro
Firebird/InterBase
Informix
IBM DB2 (IBM DB2, Cloudscape, and Apache Derby)
Ingres Database (Ingres II)
MaxDB
mSQL
Microsoft SQL Server

MySQL
Oracle OCI8
Ovrimos SQL
Paradox File Access
PostgreSQL
SQLite
Sybase
That ’ s quite an impressive list, isn ’ t it? And there ’ s a pretty good chance that if a new database were to
come around, then someone would write functions that would enable PHP to work with it. Database
integration has always been one of PHP ’ s strong points.
However, the first point of contention here is that each database extension offers a different set of
functions.
mysql_query() is used to execute a database query against MySQL, but it cannot execute a
query against Ingres II. When you change your back - end database solution, you must also update your
code to use the appropriate functions.
The second point of contention is that most, but not all, of the extensions for the databases listed earlier
follow the same general naming conventions for their functions. You would use the
ingres_query()
function to execute a query against Ingres II, but Oracle, for example, doesn ’ t even have a
_query() function.
You have to use
ora_parse() on the SQL statement and then run ora_exec() .
You must also consider that there may be some specific functions you are using in MySQL that have no
equivalent function in your new database. Perhaps you are even using very specific SQL statements in
MySQL that are not supported in other databases, or are executed in a different way. Flexibility and
complexity often come along as a pair.
Wouldn ’ t it be cool if there were a way to write your code more abstractly, so that when you run a function
such as
get_query_results() , it would be smart enough to know what type of database you are
connecting to and perform all of the necessary steps to retrieve the data? That ’ s what the PHP Data Objects

(PDO) extension attempts to do — provide a seamless experience when using PHP to communicate across
different databases. PDO provides a data - abstraction layer so that you can use the same set of functions to
work with a database, regardless of what database back end your company is using.















bapp08.indd 770bapp08.indd 770 12/10/08 5:28:17 PM12/10/08 5:28:17 PM
771
Appendix H: An Introduction to PHP Data Objects
That ’ s great! So why didn ’ t we share this with you sooner? The sad fact is that some hosting providers
may not make PDO available to their customers. And while we strongly urge you to use the latest
version of PHP for increased stability, security, and speed, many hosting companies still use older
versions of PHP to support legacy applications. You will be trapped into using what is offered to you,
unless you are hosting your own server.
It was only after much deliberation and discussion that we chose to continue showing you the
mysql_*
functions in this edition. PDO is the latest and the greatest, but
mysql_* is the lowest common

denominator, and we wanted to make this book relevant for the largest audience possible. We encourage
you to learn both ways, to increase your knowledge of PHP, so that you can apply either solution
depending on your needs. We also chose to present PDO to you towards the end of the book, after
you ’ ve had some experience with objected - oriented programming, because PDO uses OOP syntax. So,
let ’ s take a good look at PDO requirements and get started using it.
PHP Data Objects ( PDO ) Requirements
First of all, you must be using at least PHP 5 to take advantage of PDO, because the extension depends
on certain key features that aren ’ t available in earlier versions of PHP. Any version of PHP before version
5 will not work. PDO is available as a separate extension for PHP 5.0, and has shipped in the default
build of PHP starting with version 5.1. Of course, you ’ ll be all set on this front if you ’ re using version 6
(which we assume you are, since you ’ re reading Beginning PHP6, Apache, MySQL Web Development ).
Linux users shouldn ’ t have to do anything out of the ordinary for PDO to be available, and Windows
users just need to uncomment the
extension=php_pdo.dll line in their php.ini , for PDO to be
available. PDO also needs a database - specific driver for each type of database you plan on working with.
This driver file allows the PDO extension to translate the PHP function calls to something more specific
for the target database. For example, the
PDO_MYSQL driver is used for a MySQL database, the PDO_
INFORMIX
driver is used for an Informix database, the PDO_OCI driver is used for an Oracle database,
and so on. There is no specific
PDO_INGRES driver, but you can access the Ingres II database via the PDO_
ODBC
driver. New drivers are being developed for different databases even as you read this, so for the
most up - to - date list of drivers, you should visit
- drivers .
Your
php.ini file should list the appropriate driver as an extension, regardless of your operating system
platform. Complete instructions are available for installing drivers in the PHP online documentation.
Using PDO

With the core of PHP providing the internal mechanisms on which PDO relies, with PDO available as a
PHP extension, and with the necessary driver file installed as an extension to translate common function
calls to database - specific calls, you should be set and ready to start issuing those queries.
When you supplied a username, password, and hostname to connect to MySQL, you used the
mysql_
connect()
function. You then supplied the name of the database you wanted to work with, using

mysql_select_db() . All this information is gathered together when you are working with PDO instead
of calling two functions. The database type, hostname, and database table set are formatted as a string
bapp08.indd 771bapp08.indd 771 12/10/08 5:28:17 PM12/10/08 5:28:17 PM
772
Appendix H: An Introduction to PHP Data Objects
called a Data Source Name (DSN). There are a few different ways to format a DSN, but here is probably
the easiest way to accomplish it:

mysql:host=localhost;dbname=mywebapp

This DSN is used to establish a connection to a MySQL server running on the localhost, and you are
connecting to a database named test. You pass the DSN, username, and password to the PDO constructor
when you create a new instance of the object, like this:

$db = new PDO(‘mysql:host=localhost;dbname=mywebapp’, ‘dbuser’, ‘dbpassword’);

You then prepare a statement to be sent to the database, using the prepare() method, which returns a

PDOStatement object.
$query = ‘SELECT * FROM users’;
$stmt = $db- > prepare($query);


The prepared query is sent to the database with the execute() method.
$stmt- > execute();

So you ’ ve seen how relatively easy it is to use PDO to issue a query to a database, but the fun doesn ’ t
stop there. PDO also lets you prepare your SQL statements with placeholders and later bind data to
them when you are ready to issue the query. This lets you think of your query more as a template that is
prepared once by PDO and can be repeatedly run with different data, which is generally a more efficient
approach than if you executed several statements sequentially that differed only in their data.
Another benefit (and perhaps more important feature) of working with prepared statements is that PDO
will handle quoting and escaping of the parameters ’ data. This makes it much easier to protect your
database against malicious input sneaking in.
When you prepare a statement, you can provide parameters as placeholders in your SQL. These
parameters can either be represented with a
? or be explicitly named. Let ’ s take a look at using ? as a
placeholder in a query.

$query = ‘INSERT INTO users
(username, first_name, last_name, email)
VALUES
(?, ?, ?, ?)’;
$stmt = $db- > prepare($query);
$stmt- > execute(array($username, $first_name, $last_name, $email));

The values that will replace the ? placeholders in the query are passed as an array to the execute()
method. The values appear in the array in the same order in which they will replace the placeholders.
bapp08.indd 772bapp08.indd 772 12/10/08 5:28:17 PM12/10/08 5:28:17 PM
773
Appendix H: An Introduction to PHP Data Objects
Named parameters can be used in a similar way, except that the names are used as keys in the array, so
the order of the data elements is not as important. The parameter identifiers are prefixed with

: in the
query.

$query = ‘INSERT INTO users
(username, first_name, last_name, email)
VALUES
(:username, :first_name, :last_name, :email)’;
$stmt = $db- > prepare($query);
$stmt- > execute(array(‘:username’ = > $username,
‘:first_name’ = > $first_name,
‘:last_name’ = > $last_name,
‘:email’ = > $email));

Compare these with how you would need to execute the same query using mysql_* functions, and you
will see that PDO is more efficient, convenient, and flexible than the other database access extensions. It
also makes your code more readable, which is a good thing, because it is then easier to debug and
maintain.

$query = ‘INSERT INTO users
(username, first_name, last_name, email)
VALUES
(“’ . mysql_real_escape_string($username, $db) . ‘”,
(“’ . mysql_real_escape_string($first_name, $db) . ‘”,
(“’ . mysql_real_escape_string($last_name, $db) . ‘”,
(“’ . mysql_real_escape_string($email, $db) . ‘”)’;
$result = mysql_query($query, $db);

A PDOStatement is an interesting object, in that at first it represents a prepared statement. After you
execute that statement, the object then represents the associated result set. You can call the statement ’ s


fetch() method to retrieve your results. Alternatively, you can use the fetchAll() method to retrieve
all the records at one time as an array.
The
PDOStatement object ’ s fetch() and fetchAll() methods are more versatile than you may
initially think. The methods accept arguments that affect how you access the results that are returned
from the database. Both accept the following constants as an argument:

PDO::FETCH_ASSOC returns the results as an associative array.

PDO::FETCH_BOTH returns the results as an array indexed by both column name and numeric
values. This is the default behavior, if no other mode is specified.

PDO::FETCH_BOUND assigns the result ’ s values back to the PHP variables to which they were
bound.

PDO::FETCH_CLASS returns a new instance of a class with the results mapped to the object ’ s
properties.

PDO::FETCH_CLASSTYPE can be combined with PDO::FETCH_CLASS , and the name of the class
will be determined by the value of the first column in the result set.

PDO::FETCH_INTO updates an existing object with values from the result set.






bapp08.indd 773bapp08.indd 773 12/10/08 5:28:18 PM12/10/08 5:28:18 PM
774

Appendix H: An Introduction to PHP Data Objects
PDO::FETCH_LAZY is a combination of PDO::FETCH_BOTH and PDO::FETCH_OBJ .

PDO::FETCH_NUM returns the results as a numerically indexed array.

PDO::FETCH_OBJ returns an anonymous object with the results mapped to the object ’ s
properties.

while ($row = $stmt- > fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}

Another useful method of the PDOStatement object is rowCount() . It is comparable to mysql_num_
rows()
, and returns the number of rows affected by an INSERT , UPDATE , or DELETE query or returned
by a
SELECT query.
$query = ‘SELECT * FROM users’;
$stmt = $db- > prepare($query);
$stmt- > execute();
echo ‘There are ‘ . $stmt- > rowCount() . ‘ users.’;

You have seen several instances throughout this book where you want to retrieve the primary key of a
record after you insert it into the database. For example, when you are creating a new user ’ s record and
want to associate various permissions with him or her but store the permissions in a separate table, you
will often link them together by the user ’ s ID. After you insert the user ’ s information into a users table,
you need to retrieve the new user ID so you can continue adding information in other tables. You
employ the
PDO object ’ s lastInsertId() method for this, which is comparable to the mysql_insert_
id()

function.
$query = ‘INSERT INTO users
(username, first_name, last_name, email)
VALUES
(:username, :first_name, :last_name, :email)’;
$stmt = $db- > prepare($query);
$stmt- > execute(array(‘:username’ = > $username,
‘:first_name’ = > $first_name,
‘:last_name’ = > $last_name,
‘:email’ = > $email));
$user_id = $db- > lastInsertId();
$query = ‘INSERT INTO addresses
(user_id, address_1, address_2, city, state, zip_code)
VALUES
(:user_id, :address_1, :address_2, :city, :state, :zip_code)’;
$stmt = $db- > prepare($query);
$stmt- > execute(array(‘:user_id’ = > $user_id,
‘:address_1’ = > $address_1,
‘:address_2’ = > $address_2,
‘:city’ = > $city,
‘:state’ = > $state,
‘:zip_code’ = > $zip_code));




bapp08.indd 774bapp08.indd 774 12/10/08 5:28:18 PM12/10/08 5:28:18 PM
775
Appendix H: An Introduction to PHP Data Objects
There is no method equivalent to mysql_close() to disconnect from the database with PDO. Instead,

you simply set your reference to the
PDO object to null. PHP will close the connection on your behalf
when the reference is no longer needed.

$db = null;

You can find more information on PHP ’ s PDO extension and its PDO and PDOStatement objects in the
official documentation online at
www.php.net/pdo .
Summary
Now that you know how to use PDO, you can go ahead and start writing your PHP applications using
the PDO interface. So long as you keep your database queries themselves restricted to a subset of SQL
commands that are supported by MySQL or any other database solution you choose — whether it be
Sybase, Microsoft SQL Server, Oracle, Ingres II, or whatever other solution your company may throw
your way — all you need to do is make sure you have the appropriate driver file listed as an extension,
and you can avoid having to rewrite all of your PHP code. You won ’ t even break a sweat when the IT
manager informs you of the company ’ s decision to switch everyone from Ingres II to PostgreSQL after
the marketing department installs their new tracking system.
Each database understands its own unique dialect of SQL, and finding that subset of common keywords
can be limiting. If your company has chosen to go with MySQL over PostgreSQL, or Ingres II over
MySQL, it was probably for a reason. You will probably be writing queries that maximize your particular
database ’ s strengths and won ’ t necessarily be directly compatible with other databases. Each of your
queries will need to be reviewed when you change to another database. At least you won ’ t have to
rewrite your PHP code when you use PDO, though, and that ’ s half the battle. Learning PDO will only
make you a stronger developer and give you more options to choose from. Just remember its limitations,
how you can use it with specific versions of PHP only, and how it ’ s configured to work properly.
bapp08.indd 775bapp08.indd 775 12/10/08 5:28:18 PM12/10/08 5:28:18 PM

×