PHP and MySQL Web development 4th ed Edition Luke Welling pdf download
PHP and MySQL Web development 4th ed Edition Luke Welling pdf download
https://ebookgate.com/product/php-and-mysql-web-development-4th-
ed-edition-luke-welling/
https://ebookgate.com/product/php-and-mysql-web-development-luke-
welling/
ebookgate.com
https://ebookgate.com/product/php-and-mysql-web-development-third-
edition-luke-welling/
ebookgate.com
https://ebookgate.com/product/professional-lamp-linux-apache-mysql-
and-php-web-development-1st-edition-jason-gerner/
ebookgate.com
https://ebookgate.com/product/learning-php-mysql-and-javascript-1st-
ed-edition-robin-nixon/
ebookgate.com
MySQL PHP Database Applications 2nd ed Edition Brad Bulger
https://ebookgate.com/product/mysql-php-database-applications-2nd-ed-
edition-brad-bulger/
ebookgate.com
https://ebookgate.com/product/php-mysql-for-dummies-3rd-ed-edition-
janet-valade/
ebookgate.com
https://ebookgate.com/product/the-php-programming-with-mysql-the-web-
technology-series-the-web-technologies-series-2nd-edition-don-
gosselin/
ebookgate.com
PHP for the Web Visual QuickStart Guide 4th Edition Larry
Ullman
https://ebookgate.com/product/php-for-the-web-visual-quickstart-
guide-4th-edition-larry-ullman/
ebookgate.com
https://ebookgate.com/product/php-mysql-for-advanced-learning-3rd-
edition-hirdesh-bhardwaj/
ebookgate.com
00_0672329166_fm.qxd 9/3/08 1:14 PM Page i
“I’ve never purchased a better “I picked up this book two days ago
programming book… This book proved to and I am half way finished. I just can’t put
be the most informative, easiest to follow, it down.The layout and flow is perfect.
and had the best examples of any other Everything is presented in such a way so
computer-related book I have ever that the information is very palatable. I am
purchased.The text is very easy to follow!” able to immediately grasp all the concepts.
—Nick Landman The examples have also been wonderful.
I just had to take some time out to express
“This book by Welling & Thomson is the to you how pleased I have been with
only one which I have found to be indis- this book.”
pensable.The writing is clear and straightfor- —Jason B. Lancaster
ward but never wastes my time.The book is
extremely well laid out.The chapters are the “This book has proven a trusty
right length and chapter titles quickly take companion, with an excellent crash course
you where you want to go.” in PHP and superb coverage of MySQL as
—Wright Sullivan, President, A&E used for Web applications. It also features
Engineering, Inc., Greer South Carolina several complete applications that are great
examples of how to construct modular,
“I just wanted to tell you that I think the scalable applications with PHP.Whether
book PHP and MySQL Web Development you are a PHP newbie or a veteran in
rocks! It’s logically structured, just the right search of a better desk-side reference, this
difficulty level for me (intermediate), one is sure to please!”
interesting and easy to read, and, of course, —WebDynamic
full of valuable information!”
—CodE-E, Austria “The true PHP/MySQL bible, PHP
and MySQL Web Development by Luke
“There are several good introductory Welling and Laura Thomson, made me
books on PHP, but Welling & Thomson is an realize that programming and databases are
excellent handbook for those who wish to now available to the commoners. Again, I
build up complex and reliable systems. It’s know 1/10000th of what there is to know,
obvious that the authors have a strong back- and already I’m enthralled.”
ground in the development of professional —Tim Luoma,TnTLuoma.com
applications and they teach not only
the language itself, but also how to use it “Welling and Thomson’s book is a good
with good software engineering practices.” reference for those who want to get to
—Javier Garcia, senior telecom engineer, grips with practical projects straight off the
Telefonica R&D Labs, Madrid bat. It includes webmail, shopping cart,
session control, and web-forum/weblog
applications as a matter of course, and
begins with a sturdy look at PHP first,
moving to MySQL once the basics
are covered.”
—twilight30 on Slashdot
00_0672329166_fm.qxd 9/3/08 1:14 PM Page ii
“One of the best programming guides “This book is God…. I highly recom-
I’ve ever read.” mend this book to anyone who wants to
—jackofsometrades from Lahti, Finland jump in the deep end with database driven
Web application programming. I wish more
computer books were organized this way.”
—Sean C Schertell
00_0672329166_fm.qxd 9/3/08 1:14 PM Page iii
Web Development
Fourth Edition
00_0672329166_fm.qxd 9/3/08 1:14 PM Page iv
00_0672329166_fm.qxd 9/3/08 1:14 PM Page v
Web Development
Fourth Edition
Luke Welling
Laura Thomson
❖
To our Mums and Dads
❖
00_0672329166_fm.qxd 9/3/08 1:14 PM Page viii
Contents at a Glance
Introduction 1
I Using PHP
1 PHP Crash Course 13
2 Storing and Retrieving Data 59
3 Using Arrays 81
4 String Manipulation and Regular Expressions 107
5 Reusing Code and Writing Functions 133
6 Object-Oriented PHP 159
7 Error and Exception Handling 193
II Using MySQL
8 Designing Your Web Database 207
9 Creating Your Web Database 219
10 Working with Your MySQL Database 243
11 Accessing Your MySQL Database from the Web
with PHP 267
12 Advanced MySQL Administration 287
13 Advanced MySQL Programming 311
VI Appendixes
A Installing PHP and MySQL 889
B Web Resources 907
Index 911
00_0672329166_fm.qxd 9/3/08 1:14 PM Page x
Table of Contents
Introduction 1
I Using PHP
Assignment Operators 34
Comparison Operators 36
Logical Operators 38
Bitwise Operators 38
Other Operators 39
Working Out the Form Totals 41
Understanding Precedence and Associativity 42
Using Variable Functions 44
Testing and Setting Variable Types 44
Testing Variable Status 45
Reinterpreting Variables 46
Making Decisions with Conditionals 46
if Statements 46
Code Blocks 47
else Statements 47
elseif Statements 48
switch Statements 49
Comparing the Different Conditionals 51
Repeating Actions Through Iteration 51
while Loops 53
for and foreach Loops 54
do...while Loops 55
Breaking Out of a Control Structure or Script 56
Employing Alternative Control Structure Syntax 56
Using declare 57
Next 57
xii Contents
Writing to a File 67
Parameters for fwrite() 68
File Formats 68
Closing a File 69
Reading from a File 71
Opening a File for Reading: fopen() 72
Knowing When to Stop: feof() 73
Reading a Line at a Time: fgets(), fgetss(), and
fgetcsv() 73
Reading the Whole File: readfile(), fpassthru(), and
file() 74
Reading a Character: fgetc() 75
Reading an Arbitrary Length: fread() 75
Using Other Useful File Functions 76
Checking Whether a File Is There:
file_exists() 76
Determining How Big a File Is: filesize() 76
Deleting a File: unlink() 76
Navigating Inside a File: rewind(), fseek(), and
ftell() 76
Locking Files 78
A Better Way: Database Management Systems 79
Problems with Using Flat Files 79
How RDBMSs Solve These Problems 80
Further Reading 80
Next 80
3 Using Arrays 81
What Is an Array? 81
Numerically Indexed Arrays 82
Initializing Numerically Indexed Arrays 82
Accessing Array Contents 83
Using Loops to Access the Array 84
Arrays with Different Indices 85
Initializing an Array 85
Accessing the Array Elements 85
Using Loops 85
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xiii
Contents xiii
Array Operators 87
Multidimensional Arrays 88
Sorting Arrays 92
Using sort() 92
Using asort() and ksort() to Sort Arrays 93
Sorting in Reverse 93
Sorting Multidimensional Arrays 93
User-Defined Sorts 93
Reverse User Sorts 95
Reordering Arrays 96
Using shuffle() 96
Using array_reverse() 97
Loading Arrays from Files 98
Performing Other Array Manipulations 102
Navigating Within an Array: each(), current(),
reset(), end(), next(), pos(), and prev() 102
Applying Any Function to Each Element in an
Array: array_walk() 103
Counting Elements in an Array: count(), sizeof(),
and array_count_values() 104
Converting Arrays to Scalar Variables:
extract() 105
Further Reading 106
Next 106
xiv Contents
Contents xv
xvi Contents
Overriding 170
Preventing Inheritance and Overriding with final
172
Understanding Multiple Inheritance 173
Implementing Interfaces 173
Designing Classes 174
Writing the Code for Your Class 175
Understanding Advanced Object-Oriented
Functionality in PHP 183
Using Per-Class Constants 184
Implementing Static Methods 184
Checking Class Type and Type Hinting 184
Late Static Bindings 185
Cloning Objects 186
Using Abstract Classes 186
Overloading Methods with __call() 186
Using __autoload() 187
Implementing Iterators and Iteration 188
Converting Your Classes to Strings 190
Using the Reflection API 190
Next 191
II Using MySQL
Contents xvii
Rows 209
Values 209
Keys 209
Schemas 210
Relationships 211
Designing Your Web Database 211
Think About the Real-World Objects You Are
Modeling 211
Avoid Storing Redundant Data 212
Use Atomic Column Values 214
Choose Sensible Keys 215
Think About What You Want to Ask the
Database 215
Avoid Designs with Many Empty
Attributes 215
Summary of Table Types 216
Web Database Architecture 216
Further Reading 218
Next 218
xviii Contents
Contents xix
xx Contents
Contents xxi
xxii Contents
Firewalls 357
Data Backups 358
Backing Up General Files 358
Backing Up and Restoring Your MySQL
Database 358
Physical Security 359
Next 359
Contents xxiii
xxiv Contents
Contents xxv
xxvi Contents
Contents xxvii
xxviii Contents
26 Debugging 551
Programming Errors 551
Syntax Errors 552
Runtime Errors 553
Logic Errors 558
Variable Debugging Aid 559
Error Reporting Levels 562
Altering the Error Reporting Settings 563
Triggering Your Own Errors 564
Handling Errors Gracefully 565
Next 567
Contents xxix
xxx Contents
Contents xxxi
xxxii Contents
Contents xxxiii
xxxiv Contents
Appendixes
Index 911
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxv
Lead Authors
Laura Thomson is a senior software engineer at Mozilla Corporation. She was former-
ly a principal at both OmniTI and Tangled Web Design, and she has worked for RMIT
University and the Boston Consulting Group. She holds a Bachelor of Applied Science
(Computer Science) degree and a Bachelor of Engineering (Computer Systems
Engineering) degree with honors. In her spare time she enjoys riding horses, arguing
about free and open source software, and sleeping.
Luke Welling is a web architect at OmniTI and regularly speaks on open source and
web development topics at conferences such as OSCON, ZendCon, MySQLUC,
PHPCon, OSDC, and LinuxTag. Prior to joining OmniTI, he worked for the web ana-
lytics company Hitwise.com, at the database vendor MySQL AB, and as an independent
consultant at Tangled Web Design. He has taught computer science at RMIT University
in Melbourne, Australia, and holds a Bachelor of Applied Science (Computer Science)
degree. In his spare time, he attempts to perfect his insomnia.
Contributing Authors
Julie C. Meloni is the technical director for i2i Interactive (www.i2ii.com), a multime-
dia company located in Los Altos, California. She has been developing web-based
applications since the Web first saw the light of day and remembers the excitement
surrounding the first GUI web browser. She has authored numerous books and articles
on web-based programming languages and database topics, including the bestselling Sams
Teach Yourself PHP, MySQL, and Apache All in One.
Marc Wandschneider is a freelance software developer, author, and speaker who travels
the globe working on interesting projects. In recent years, a lot of his attention has
been focused on writing robust and scalable web applications, and in 2005 he wrote a
book called Core Web Application Programming with PHP and MySQL. He was was previ-
ously the main developer of the SWiK (http://swik.net) open source community site.
Marc currently lives in Beijing where he spends his time mangling the Chinese language
and programming.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxvi
Acknowledgments
We would like to thank the team at Pearson for all their hard work. In particular, we
would like to thank Shelley Johnston, without whose dedication and patience the first
three editions of this book would not have been possible, and Mark Taber, who has taken
over for the fourth edition.
We appreciate immensely the work done by the PHP and MySQL development
teams.Their work has made our lives easier for a number of years now and continues to
do so on a daily basis.
We thank Adrian Close at eSec for saying “You can build that in PHP” back in 1998.
He said we would like PHP, and it seems he was right.
Finally, we would like to thank our family and friends for putting up with us while
we have been repeatedly antisocial while working on books. Specifically, thank you for
your support to our family members: Julie, Robert, Martin, Lesley, Adam, Paul, Archer,
and Barton.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxvii
Reader Services
Visit our website and register this book at informit.com/register for convenient access to
any updates, downloads, or errata that might be available for this book.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxviii
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 1
Introduction
W ELCOME TO PHP AND MYSQL WEB DEVELOPMENT. Within its pages, you will find
distilled knowledge from our experiences using PHP and MySQL, two of the hottest
web development tools around.
In this introduction, we cover
n Why you should read this book
n What you will be able to achieve using this book
n What PHP and MySQL are and why they’re great
n What’s changed in the latest versions of PHP and MySQL
n How this book is organized
2 Introduction
You should be able to use any of these projects as is, or you can modify them to suit
your needs.We chose them because we believe they represent some the most common
web-based applications built by programmers. If your needs are different, this book
should help you along the way to achieving your goals.
What Is PHP?
PHP is a server-side scripting language designed specifically for the Web.Within an
HTML page, you can embed PHP code that will be executed each time the page is vis-
ited.Your PHP code is interpreted at the web server and generates HTML or other out-
put that the visitor will see.
PHP was conceived in 1994 and was originally the work of one man, Rasmus
Lerdorf. It was adopted by other talented people and has gone through four major
rewrites to bring us the broad, mature product we see today. As of November 2007, it
was installed on more than 21 million domains worldwide, and this number is growing
rapidly. You can see the current number at http://www.php.net/usage.php.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 3
Introduction 3
PHP is an Open Source project, which means you have access to the source code and
can use, alter, and redistribute it all without charge.
PHP originally stood for Personal Home Page but was changed in line with the GNU
recursive naming convention (GNU = Gnu’s Not Unix) and now stands for PHP
Hypertext Preprocessor.
The current major version of PHP is 5.This version saw a complete rewrite of the
underlying Zend engine and some major improvements to the language.
The home page for PHP is available at http://www.php.net.
The home page for Zend Technologies is http://www.zend.com.
What Is MySQL?
MySQL (pronounced My-Ess-Que-Ell ) is a very fast, robust, relational database management
system (RDBMS). A database enables you to efficiently store, search, sort, and retrieve
data.The MySQL server controls access to your data to ensure that multiple users can
work with it concurrently, to provide fast access to it, and to ensure that only authorized
users can obtain access. Hence, MySQL is a multiuser, multithreaded server. It uses
Structured Query Language (SQL), the standard database query language. MySQL has been
publicly available since 1996 but has a development history going back to 1979. It is the
world’s most popular open source database and has won the Linux Journal Readers’
Choice Award on a number of occasions.
MySQL is available under a dual licensing scheme.You can use it under an open
source license (the GPL) free as long as you are willing to meet the terms of that license.
If you want to distribute a non-GPL application including MySQL, you can buy a com-
mercial license instead.
Some of these choices are dependent on the others. For example, not all operating
systems run on all hardware, not all web servers support all programming languages, and
so on.
In this book, we do not pay much attention to hardware, operating systems, or web
server software.We don’t need to. One of the best features of both PHP and MySQL is
that they work with any major operating system and many of the minor ones.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 4
4 Introduction
The majority of PHP code can be written to be portable between operating systems
and web servers.There are some PHP functions that specifically relate to the filesystem
that are operating system dependent, but these are clearly marked as such in the manual
and in this book.
Whatever hardware, operating system, and web server you choose, we believe you
should seriously consider using PHP and MySQL.
Performance
PHP is very fast. Using a single inexpensive server, you can serve millions of hits per day.
Benchmarks published by Zend Technologies (http://www.zend.com) show PHP out-
performing its competition.
Scalability
PHP has what Rasmus Lerdorf frequently refers to as a “shared-nothing” architecture.
This means that you can effectively and cheaply implement horizontal scaling with large
numbers of commodity servers.
Database Integration
PHP has native connections available to many database systems. In addition to MySQL,
you can directly connect to PostgreSQL, Oracle, dbm, FilePro, DB2, Hyperwave,
Informix, InterBase, and Sybase databases, among others. PHP 5 also has a built-in SQL
interface to a flat file, called SQLite.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 5
Introduction 5
Using the Open Database Connectivity Standard (ODBC), you can connect to any data-
base that provides an ODBC driver.This includes Microsoft products and many others.
In addition to native libraries, PHP comes with a database access abstraction layer
called PHP Database Objects (PDO), which allows consistent access and promotes secure
coding practices.
Built-in Libraries
Because PHP was designed for use on the Web, it has many built-in functions for per-
forming many useful web-related tasks.You can generate images on the fly, connect to
web services and other network services, parse XML, send email, work with cookies, and
generate PDF documents, all with just a few lines of code.
Cost
PHP is free.You can download the latest version at any time from http://www.php.net
for no charge.
Object-Oriented Support
PHP version 5 has well-designed object-oriented features. If you learned to program in
Java or C++, you will find the features (and generally the syntax) that you expect, such
as inheritance, private and protected attributes and methods, abstract classes and methods,
interfaces, constructors, and destructors.You will even find some less common features
such as iterators. Some of this functionality was available in PHP versions 3 and 4, but
the object-oriented support in version 5 is much more complete.
Portability
PHP is available for many different operating systems.You can write PHP code on free
Unix-like operating systems such as Linux and FreeBSD, commercial Unix versions such
as Solaris and IRIX, OS X, or on different versions of Microsoft Windows.
Well-written code will usually work without modification on a different system run-
ning PHP.
6 Introduction
Source Code
You have access to PHP’s source code.With PHP, unlike commercial, closed-source
products, if you want to modify something or add to the language, you are free to do so.
You do not need to wait for the manufacturer to release patches.You also don’t need
to worry about the manufacturer going out of business or deciding to stop supporting a
product.
Other changes include moving some extensions out of the default PHP install and into
the PECL library, improving streams support, and adding SQLite.
At the time of writing, PHP 5.2 was the current version, with PHP 5.3 on the near
horizon. PHP 5.2 added a number of useful features including:
n The new input filtering extension for security purposes
n JSON extension for better JavaScript interoperability
n File upload progress tracking
n Better date and time handling
n Many upgraded client libraries, performance improvements (including better
memory management in the Zend Engine), and bug fixes
Introduction 7
installing it for mass use for quite some time. However, some of the key features planned
in PHP 6 have been back-ported to PHP 5.3, which is a minor version release and clos-
er to passing acceptance testing and thus installation by hosting providers (of course, if
you are your own server’s administrator, you can install any version you like).
Some of the new features in PHP 5.3 are listed below; additional information also
appears throughout this book as appropriate:
n The addition of namespaces; for more information see http://www.php.net/
language.namespaces
n The addition of the intl extension for application internationalization; for more
information see http://www.php.net/manual/en/intro.intl.php
n The addition of the phar extension for creating self-contained PHP application
archives; for more information see http://www.php.net/book.phar
n The addition of the fileinfo extension for enhanced ability to work with files;
for more information see http://www.php.net/manual/en/book.fileinfo.php
n The addition of the sqlite3 extension for working with the SQLite Embeddable
SQL Database Engine; for more information see http://www.php.net/manual/en/
class.sqlite3.php
n The inclusion of support for the MySQLnd driver, a replacement for libmysql; for
more information see http://forge.mysql.com/wiki/PHP_MYSQLND
While the list above contains some of the highly-touted features of PHP 5.3, the release
also includes a significant number of bug fixes and maintenance performed on existing
functionality, such as:
n Removing support for any version of Windows older than Windows 2000 (such as
Windows 98 and NT4)
n Ensuring the PCRE, Reflection, and SPL extensions are always enabled
n Adding a few date and time functions for ease of date calculation and manipula-
tion
n Improving the crypt(), hash(), and md5() functionality, as well as improving the
OpenSSL extension
n Improving php.ini administration and handling, including better error reporting
n Continuing to fine-tune the Zend engine for better PHP runtime speed and
memory usage
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
ebookgate.com