PHP 6 MYSQL programming for the absolute beginner
1st Edition Andrew B. (Andrew B. Harris) Harris fast
download
Find it at ebookgate.com
( 4.7/5.0 ★ | 154 downloads )
https://ebookgate.com/product/php-6-mysql-programming-for-the-
absolute-beginner-1st-edition-andrew-b-andrew-b-harris-harris/
PHP 6 MYSQL programming for the absolute beginner 1st
Edition Andrew B. (Andrew B. Harris) Harris
EBOOK
Available Formats
■ PDF eBook Study Guide Ebook
EXCLUSIVE 2025 ACADEMIC EDITION – LIMITED RELEASE
Available Instantly Access Library
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
C Programming for the Absolute Beginner 3rd Edition Keith
Davenport
https://ebookgate.com/product/c-programming-for-the-absolute-
beginner-3rd-edition-keith-davenport/
ebookgate.com
Visual Basic Programming for the Absolute Beginner 1st
Edition Michael Vine
https://ebookgate.com/product/visual-basic-programming-for-the-
absolute-beginner-1st-edition-michael-vine/
ebookgate.com
Microsoft Access VBA programming for the absolute beginner
3rd Edition Michael (Michael Vine) Vine
https://ebookgate.com/product/microsoft-access-vba-programming-for-
the-absolute-beginner-3rd-edition-michael-michael-vine-vine/
ebookgate.com
Absolute Beginner s Guide to Programming 2nd Edition Greg
Perry
https://ebookgate.com/product/absolute-beginner-s-guide-to-
programming-2nd-edition-greg-perry/
ebookgate.com
PHP Mysql For Advanced Learning 3rd Edition Hirdesh
Bhardwaj
https://ebookgate.com/product/php-mysql-for-advanced-learning-3rd-
edition-hirdesh-bhardwaj/
ebookgate.com
PHP MySQL For Dummies 3rd ed Edition Janet Valade
https://ebookgate.com/product/php-mysql-for-dummies-3rd-ed-edition-
janet-valade/
ebookgate.com
Checkmate 6 1st Edition Owen B. Greenwald
https://ebookgate.com/product/checkmate-6-1st-edition-owen-b-
greenwald/
ebookgate.com
The PHP Programming with MySQL The Web Technology Series
The Web Technologies Series 2nd Edition Don Gosselin
https://ebookgate.com/product/the-php-programming-with-mysql-the-web-
technology-series-the-web-technologies-series-2nd-edition-don-
gosselin/
ebookgate.com
The Happiness Trap 1st Edition Harris
https://ebookgate.com/product/the-happiness-trap-1st-edition-harris/
ebookgate.com
PHP 6/MySQL Programming for the © 2009 Course Technology, a part of Cengage Learning.
Absolute Beginner: Andy Harris
ALL RIGHTS RESERVED. No part of this work covered by the copyright
Publisher and General Manager, Course herein may be reproduced, transmitted, stored, or used in any form or by
Technology PTR: Stacy L. Hiquet any means graphic, electronic, or mechanical, including but not limited to
photocopying, recording, scanning, digitizing, taping, Web distribution,
Associate Director of Marketing:
information networks, or information storage and retrieval systems, except
Sarah Panella
as permitted under Section 107 or 108 of the 1976 United States Copyright
Manager of Editorial Services: Act, without the prior written permission of the publisher.
Heather Talbot
Marketing Manager: Mark Hughes For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
Acquisitions Editor: Mitzi Koontz
For permission to use material from this text or product, submit all
Project Editor: Jenny Davidson requests online at cengage.com/permissions Further permissions
questions can be emailed to [email protected]
Technical Reviewer: Matt Telles
PTR Editorial Services Coordinator:
Erin Johnson PHP is a copyright of the PHP Group. MySQL is a registered trademark of
MySQL AB in the United States, the European Union and other countries.
Interior Layout Tech: Value Chain Firefox and Maguma Open Studio are registered trademarks of the Mozilla
Foundation. HTML Validator is a registered trademark of the Massachusetts
Cover Designer: Mike Tanamachi
Institute of Technology, European Research Consortium for Informatics and
CD-ROM Producer: Brandon Penticuff Mathematics, or Keio University on behalf of the World Wide Web Consor-
tium. Aptana is a registered trademark of Aptana, Inc.
Indexer: Larry Sweazy
All other trademarks are the property of their respective owners.
Proofreader: Sara Gullion
Library of Congress Control Number: 2008928831
ISBN-13: 978-1-59863-798-4
ISBN-10: 1-59863-798-3
eISBN-10: 1-59863-826-2
Course Technology
25 Thomson Place
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions
with office locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by Nelson
Education, Ltd.
For your lifelong learning solutions, visit courseptr.com
Visit our corporate website at cengage.com
Printed in Canada
1 2 3 4 5 6 7 11 10 09
To Heather, Elizabeth, Matthew, Jacob, and Benjamin, and to
all those who have called me Teacher.
ACKNOWLEDGMENTS
F
irst, I thank my Lord and Savior Jesus Christ.
Heather, you always work harder on these books than I do. Thank you for
your love and your support. Thank you Elizabeth, Matthew, Jacob, and
Benjamin for understanding why Dad was typing all the time.
Thanks to the Open Source community for creating great free software like PHP
and MySQL.
Thank you, Stacy Hiquet, for your continued support and encouragement on this
and other projects. Thanks to Mitzi Koontz, for seeing this project through, and to
Jenny Davidson for your work as the project editor. Special thanks to Matt Telles
for the outstanding technical edit. You made the book far better than it would
have been before.
Thanks to all who worked on the previous two editions. Your hard work was the
foundation for something that might be even better.
Thank you to the many members of the Course Technology PTR team who worked
on this book.
A huge thanks goes to my students throughout the years and the many people
who sent in comments and advice from the first two editions. Thank you for being
patient with my manuscript, for helping me spot many errors, and for providing
invaluable advice. I learned as much from you as you did from me.
ABOUT THE AUTHOR
A
ndy Harris began his teaching career as a high-school special education
teacher. During that time, he taught himself enough computing to do part-
time computer consulting and database work. He began teaching comput-
ing at the university level in the late 1980s as a part-time job. Since 1995 he
has been a full-time lecturer in the Computer Science Department of Indiana
University/Purdue University–Indianapolis, where he serves as a senior lecturer
and teaches classes in several programming languages. His primary interests are
web development, PHP, Java, game programming, virtual reality, portable devices,
and streaming media. He has written numerous books on these and other tech-
nology topics.
This page intentionally left blank
Table of Contents
Chapter 1 Exploring the Environment..................................... 1
Programming on the Web Server...................................................................................... 3
Installing PHP and Apache ......................................................................................... 4
Using an Existing Server.............................................................................................. 4
Installing Your Own Development Environment................................................. 5
Installing with XAMPP ................................................................................................. 7
Starting Your Server ..................................................................................................... 8
Checking Your Security Settings............................................................................... 9
Configuring Apache.................................................................................................... 10
Running Your Local Server................................................................................................ 11
Adding PHP to Your Pages......................................................................................... 11
Examining the Results ............................................................................................... 12
Display Errors ............................................................................................................... 16
Windows Extensions .................................................................................................. 17
Changes in PHP 6......................................................................................................... 19
Safe Mode....................................................................................................................... 19
Register Globals ........................................................................................................... 19
Creating the Tip of the Day Program............................................................................. 19
Summary................................................................................................................................ 20
Chapter 2 Using Variables and Input...................................... 21
Introducing the Story Program........................................................................................ 21
Using Variables in Your Scripts........................................................................................ 23
Introducing the Hi Jacob Program ......................................................................... 23
Creating a String Variable................................................................................................. 25
Naming Your Variables .............................................................................................. 25
Assigning a Value to a Variable ............................................................................... 25
Printing a Variable’s Value ....................................................................................... 26
Using Variables for More Complex Pages...................................................................... 28
Building the Row Your Boat Page ........................................................................... 28
Creating Multi-Line Strings ...................................................................................... 30
Working with Numeric Variables.................................................................................... 31
Making the ThreePlusFive Program ....................................................................... 31
viii PHP 6/MySQL Programming for the Absolute Beginner
Assigning Numeric Values ........................................................................................ 33
Using Mathematical Operators................................................................................ 33
Creating a Form to Ask a Question................................................................................. 34
Building an HTML Page with a Form ..................................................................... 35
Setting the Action Attribute to a Script File ........................................................ 36
Writing a Script to Retrieve the Data .................................................................... 37
Sending Data without a Form.......................................................................................... 39
Understanding the get Method ............................................................................... 39
Using a URL to Embed Form Data........................................................................... 40
Working with Multiple Field Queries.................................................................... 42
Building a Pre-formatted Query .............................................................................. 42
Reading Input from Other Form Elements .......................................................... 43
Introducing the borderMaker Program......................................................................... 43
Building the borderMaker.html Page .................................................................... 44
Reading the Form Elements ..................................................................................... 47
Reading Select Elements ........................................................................................... 48
Reading Radio Groups................................................................................................ 49
Returning to the Story Program...................................................................................... 50
Designing the Story .................................................................................................... 50
Building the HTML Page ............................................................................................ 52
Building the Story ....................................................................................................... 54
Summary................................................................................................................................ 56
Chapter 3 Controlling Your Code with Conditions and
Functions.................................................................. 57
Examining the Petals around the Rose Game.............................................................. 57
Creating a Random Number............................................................................................. 58
Viewing the Roll Em Program.................................................................................. 58
Printing a Corresponding Image............................................................................. 60
Using the if Statement to Control Program Flow....................................................... 61
Introducing the Ace Program .................................................................................. 61
Creating a Condition.................................................................................................. 63
Exploring Comparison Operators ........................................................................... 64
Creating an if Statement........................................................................................... 65
Working with Negative Results....................................................................................... 66
Demonstrating the Ace or Not Program........................................................................ 66
Using the else Clause.................................................................................................. 68
Working with Multiple Values......................................................................................... 69
Writing the Binary Dice Program ........................................................................... 69
Using Multiple else if Clauses .................................................................................. 71
Using the switch Structure to Simplify Programming.............................................. 72
Building the Switch Dice Program ......................................................................... 73
Using the switch Structure....................................................................................... 74
Contents ix
Combining a Form and Its Results.................................................................................. 75
Responding to Checkboxes................................................................................................ 78
Using Functions to Encapsulate Parts of the Program.............................................. 81
Examining the This Old Man Program.................................................................. 82
Creating New Functions ............................................................................................ 84
Using Parameters and Function Values......................................................................... 84
Examining the Param.php Program ...................................................................... 85
Looking at Encapsulation in the Main Code Body ............................................. 87
Returning a Value: The chorus() Function............................................................ 88
Accepting a Parameter in the verse() Function ................................................... 89
Managing Variable Scope................................................................................................... 90
Looking at the Scope Demo ...................................................................................... 91
Returning to the Petals Game.......................................................................................... 93
Starting HTML .............................................................................................................. 94
Main Body Code ........................................................................................................... 94
The printGreeting() Function ................................................................................... 95
The printDice() Function ........................................................................................... 96
The showDie() Function ............................................................................................. 97
The calcNumPetals() Function ................................................................................. 97
The printForm() Function.......................................................................................... 98
The Ending HTML Code ............................................................................................. 99
Summary................................................................................................................................ 99
Chapter 4 Loops and Arrays................................................... 101
Introducing the Poker Dice Program........................................................................... 102
Counting with the for Loop............................................................................................ 103
Initializing a Sentry Variable ................................................................................. 104
Setting a Condition to Finish the Loop ............................................................... 105
Changing the Sentry Variable................................................................................ 105
Building the Loop ...................................................................................................... 106
Modifying the for Loop ............................................................................................ 106
Using a while Loop............................................................................................................ 110
Repeating Code with a while Loop ....................................................................... 110
Recognizing Endless Loops ..................................................................................... 111
Building a Well-Behaved Loop ............................................................................... 113
Working with Basic Arrays.............................................................................................. 114
Generating a Basic Array ......................................................................................... 116
Using a Loop to Examine an Array’s Contents .................................................. 117
Using the array() Construct to Preload an Array............................................... 117
Detecting the Size of an Array ............................................................................... 118
Improving This Old Man with Arrays and Loops...................................................... 118
Building the place Array.......................................................................................... 120
Writing Out the Lyrics ............................................................................................. 121
x PHP 6/MySQL Programming for the Absolute Beginner
Using Arrays in Forms...................................................................................................... 121
Arranging an HTML Form to Create an Array ................................................... 124
Reading an Array from a Form .............................................................................. 125
Keeping Persistent Data................................................................................................... 126
Counting with Form Fields..................................................................................... 127
Storing Data in the Text Box .................................................................................. 129
Using a Hidden Field for Persistence ................................................................... 130
Using a Session Variable to Store Data........................................................................ 130
Starting the Session .................................................................................................. 133
Working with Session Data .................................................................................... 133
Using Sessions Well .................................................................................................. 134
Writing the Poker Dice Program................................................................................... 135
Setting Up the XHTML.............................................................................................. 135
Building the Main Code Body ................................................................................ 135
Starting Up the Game .............................................................................................. 136
Playing the Game ...................................................................................................... 136
Creating the First Pass Output............................................................................... 137
Building the Second Pass Output.......................................................................... 139
Creating the evaluate() Function .......................................................................... 142
Counting the Dice Values........................................................................................ 145
Counting Pairs, Twos, Threes, Fours, and Fives ................................................ 146
Looking for Two Pairs............................................................................................... 147
Looking for Three of a Kind and a Full House ................................................... 147
Checking for Four of a Kind and Five of a Kind ................................................ 148
Checking for Straights ............................................................................................. 148
Cashing Out ................................................................................................................ 149
Summary.............................................................................................................................. 150
Chapter 5 Better Arrays and String Handling.................... 151
Introducing the Word Search Program....................................................................... 151
Using the foreach Loop to Work with an Array........................................................ 153
Introducing the foreach.php Program ................................................................ 154
Creating an Associative Array........................................................................................ 155
Examining the assoc.php Program....................................................................... 156
Building an Associative Array ................................................................................ 156
Building an Associative Array with the array() Function ............................... 158
Using foreach with Associative Arrays ................................................................ 159
Using Built-In Associative Arrays................................................................................... 159
Introducing the formReader.php Program ........................................................ 160
Reading the $_REQUEST Array .............................................................................. 160
Creating a Multidimensional Array.............................................................................. 163
Building the HTML for the Basic Multidimensional Array ............................ 165
Responding to the Distance Query ....................................................................... 166
Contents xi
Making a Two-Dimensional Associative Array........................................................... 169
Building the HTML for the Associative Array .................................................... 169
Responding to the Query......................................................................................... 171
Building the Two-Dimensional Associative Array ............................................ 172
Getting Data from the Two-Dimensional Associative Array.......................... 173
Manipulating String Values............................................................................................ 173
Demonstrating String Manipulation with the Pig Latin Translator ........... 173
Building the Form ..................................................................................................... 176
Using the split() Function to Break a String into an Array ............................ 176
Trimming a String with rtrim() ............................................................................. 177
Finding a Substring with substr() ......................................................................... 177
Using strstr() to Search for One String Inside Another ................................... 178
Using the Concatenation Operator ...................................................................... 178
Finishing the Pigify Program.......................................................................................... 179
Translating Between Characters and ASCII Values .......................................... 179
Returning to the Word Search Creator........................................................................ 179
Getting the Puzzle Data from the User ............................................................... 179
Setting Up the Response Page ................................................................................ 181
Working with the Empty Data Set........................................................................ 182
Building the Program’s Main Logic ...................................................................... 182
Parsing the Word List............................................................................................... 185
Clearing the Board .................................................................................................... 186
Filling the Board ........................................................................................................ 187
Adding a Word ........................................................................................................... 189
Making a Puzzle Board............................................................................................. 195
Adding the Foil Letters............................................................................................. 196
Printing the Puzzle ................................................................................................... 197
Printing the Answer Key.......................................................................................... 199
Summary.............................................................................................................................. 200
Chapter 6 Working with Files................................................ 201
Previewing the Quiz Machine........................................................................................ 202
Entering the Quiz Machine System...................................................................... 202
Editing a Quiz............................................................................................................. 202
Taking a Quiz.............................................................................................................. 203
Seeing the Results ..................................................................................................... 204
Viewing the Quiz Log ............................................................................................... 205
Saving a File to the File System...................................................................................... 205
Introducing the saveSonnet.php Program ......................................................... 205
Opening a File with fopen() .................................................................................... 207
Creating a File Handle ............................................................................................. 208
Examining File Access Modifiers........................................................................... 208
Writing to a File......................................................................................................... 209
xii PHP 6/MySQL Programming for the Absolute Beginner
Closing a File .............................................................................................................. 209
Loading a File from the Drive System.......................................................................... 210
Introducing the loadSonnet.php Program ......................................................... 210
Beautifying Output with CSS ................................................................................. 211
Using the “r” Access Modifier ................................................................................ 212
Checking for the End of the File with feof()....................................................... 212
Reading Data from the File with fgets() .............................................................. 212
Reading a File into an Array........................................................................................... 212
Introducing the cartoonifier.php Program ........................................................ 213
Loading the File into an Array with file()............................................................ 214
Using str_replace() to Modify File Contents ....................................................... 214
Working with Directory Information.......................................................................... 215
Introducing the imageIndex.php Program ........................................................ 215
Creating a Directory Handle with openDir()...................................................... 218
Getting a List of Files with readdir()..................................................................... 218
Selecting Particular Files with preg_grep() ........................................................ 219
Using Basic Regular Expressions ........................................................................... 219
Storing the Output.................................................................................................... 221
Working with Formatted Text....................................................................................... 222
Introducing the mailMerge.php Program .......................................................... 223
Determining a Data Format ................................................................................... 223
Examining the mailMerge.php Code ................................................................... 224
Loading Data with the file() Command ............................................................... 225
Splitting a Line into an Array and to Scalar Values ......................................... 226
Creating the QuizMachine.php Program.................................................................... 226
Building the QuizMachine.php Control Page.................................................... 227
Editing a Test.............................................................................................................. 234
Taking a Quiz.............................................................................................................. 244
Grading the Quiz ....................................................................................................... 246
Creating an Answer Key........................................................................................... 247
Viewing the Log ......................................................................................................... 250
Summary.............................................................................................................................. 251
Chapter 7 Writing Programs with Objects......................... 253
Introducing the SuperHTML Object............................................................................. 253
Building a Simple Document with SuperHTML................................................ 254
Including a File ......................................................................................................... 255
Building the Web Page............................................................................................. 256
Writing Out the Page ............................................................................................... 257
Working with the Title Property........................................................................... 258
Adding Text and Tags with SuperHTML.............................................................. 259
Creating Lists the SuperHTML Way ...................................................................... 262
Building More Specialized Lists............................................................................. 264
Contents xiii
Making Tables with SuperHTML ........................................................................... 264
Creating a Basic Table .............................................................................................. 266
Creating Super Forms .............................................................................................. 267
Building Drop-Down Menus ................................................................................... 269
Understanding OOP.......................................................................................................... 271
Objects Overview ....................................................................................................... 272
Creating a Basic Object ............................................................................................ 273
Adding Methods to a Class...................................................................................... 276
Reusing Class Files .................................................................................................... 280
Inheriting from a Parent Class .............................................................................. 282
Building the SuperHTML Class....................................................................................... 285
Overall Strategy ......................................................................................................... 285
Creating the Constructor ........................................................................................ 286
Creating the Bottom of the Page........................................................................... 288
Adding Headers and Generic Tags........................................................................ 288
Creating Lists from Arrays ...................................................................................... 290
Creating Tables One Row at a Time...................................................................... 292
Creating Forms........................................................................................................... 293
Building Basic Form Objects................................................................................... 294
Building Select Objects ............................................................................................ 295
Responding to Form Input...................................................................................... 296
Summary.............................................................................................................................. 296
Chapter 8 XML and Content Management Systems............ 299
Understanding Content Management Systems......................................................... 299
Examining Existing Content Management Systems ....................................... 300
Moodle.......................................................................................................................... 301
WordPress.................................................................................................................... 301
Drupal........................................................................................................................... 302
Introducing simpleCMS................................................................................................... 303
Viewing Pages from a User’s Perspective ............................................................ 303
Examining the PHP Code ........................................................................................ 305
Looking at the Header.............................................................................................. 306
Viewing the CSS ......................................................................................................... 307
Inspecting the Menu System .................................................................................. 309
Looking at Content Blocks ...................................................................................... 310
Improving the CMS with XML........................................................................................ 311
Introducing XML........................................................................................................ 311
Working with XML.................................................................................................... 312
Understanding XML Rules ...................................................................................... 312
Examining main.xml ............................................................................................... 313
Simplifying the Menu Pages................................................................................... 314
Introducing XML Parsers................................................................................................. 314
xiv PHP 6/MySQL Programming for the Absolute Beginner
Working with Simple XML...................................................................................... 315
Working with the simpleXML API ........................................................................ 315
Creating a simpleXML Object................................................................................. 317
Viewing the XML Code ............................................................................................. 317
Accessing XML Nodes Directly ............................................................................... 318
Using a foreach Loop on a Node ............................................................................ 319
Manipulating More Complex XML with the simpleXML API......................... 319
Returning to XCMS............................................................................................................ 323
Extracting Data from the XML File....................................................................... 324
Summary.............................................................................................................................. 325
Chapter 9 Using MySQL to Create Databases..................... 327
Introducing the Adventure Generator Program....................................................... 327
Using a Database Management System....................................................................... 330
Working with MySQL........................................................................................................ 331
Installing MySQL 6.0 ................................................................................................. 331
Using the MySQL Executable.................................................................................. 331
Creating a Database.......................................................................................................... 333
Creating a Table......................................................................................................... 333
Working with String Data in MySQL ................................................................... 337
Creating a Primary Key ............................................................................................ 338
Using the DESCRIBE Command to Check a Table’s Structure ...................... 338
Inserting Values ......................................................................................................... 339
Selecting Results........................................................................................................ 340
Writing a Script to Build a Table........................................................................... 341
Creating Comments in SQL .................................................................................... 342
Dropping a Table ....................................................................................................... 342
Running a Script with SOURCE ............................................................................. 342
Working with a Database via phpMyAdmin.............................................................. 343
Connecting to a Server............................................................................................. 344
Creating and Modifying a Table.................................................................................... 345
Editing Table Data..................................................................................................... 346
Exporting a Table ...................................................................................................... 346
Creating More Powerful Queries................................................................................... 350
Limiting Columns ..................................................................................................... 352
Limiting Rows with the WHERE Clause .............................................................. 353
Adding a Condition with a WHERE Clause ........................................................ 353
Using the LIKE Clause for Partial Matches ......................................................... 354
Generating Multiple Conditions ........................................................................... 354
Sorting Results with the ORDER BY Clause........................................................ 355
Changing Data with the UPDATE Statement..................................................... 356
Returning to the Adventure Game............................................................................... 356
Designing the Data Structure ................................................................................ 357
Summary.............................................................................................................................. 359
Contents xv
Chapter 10 Connecting to Databases within PHP................. 361
Connecting to the Hero Database................................................................................. 362
Getting a Connection ............................................................................................... 363
Choosing a Database................................................................................................. 365
Creating a Query........................................................................................................ 365
Retrieving the Data................................................................................................... 366
Retrieving Data in an HTML Table................................................................................ 366
Getting Field Names ................................................................................................. 368
Parsing the Result Set .............................................................................................. 369
Returning to the AdventureGame Program....................................................... 370
Connecting to the Adventure Database .............................................................. 370
Displaying One Segment ......................................................................................... 371
Retrieving the Room Number from the Form ................................................... 375
Making the Data Connection ................................................................................. 376
Writing the buildButton() Function..................................................................... 377
Finishing the HTML .................................................................................................. 378
Viewing and Selecting Records...................................................................................... 378
Editing the Record .................................................................................................... 381
Generating Variables................................................................................................ 386
Printing the HTML Code .......................................................................................... 386
Creating the List Boxes ............................................................................................ 386
Committing Changes to the Database......................................................................... 386
Summary.............................................................................................................................. 389
Chapter 11 Data Normalization.............................................. 391
Introducing the spy Database........................................................................................ 392
The badSpy Database........................................................................................................ 392
Inconsistent Data Problems.................................................................................... 393
Problem with the Operation Information.......................................................... 394
Problems with Listed Fields.................................................................................... 394
Age Issues..................................................................................................................... 394
Designing a Better Data Structure................................................................................ 395
Defining Rules for a Good Data Design............................................................... 395
Normalizing Your Data............................................................................................ 395
First Normal Form: Eliminate Listed Fields ....................................................... 395
Second Normal Form: Eliminate Redundancies ............................................... 397
Third Normal Form: Ensure Functional Dependency ..................................... 398
Defining Relationship Types .................................................................................. 398
Recognizing One-to-One Relationships ............................................................... 399
Describing Many-to-One Relationships................................................................ 399
Recognizing Many-to-Many Relationships.......................................................... 400
Building Your Data Tables............................................................................................... 400
xvi PHP 6/MySQL Programming for the Absolute Beginner
Setting Up the System.............................................................................................. 400
Creating the agent Table ......................................................................................... 401
Inserting a Value into the agent Table ................................................................ 403
Converting birthday to age............................................................................................. 403
Introducing SQL Functions..................................................................................... 403
Finding the Current Date........................................................................................ 404
Determining Age with DATEDIFF() ....................................................................... 404
Performing Math on Function Results ................................................................ 405
Converting Number of Days to a Date................................................................. 406
Extracting Years and Months from the Date ..................................................... 406
Concatenating to Build the age Field .................................................................. 407
Building a View.................................................................................................................. 407
Creating a Reference to the operation Table ..................................................... 409
Building the operation Table ................................................................................. 409
Using a Join to Connect Tables .............................................................................. 411
Creating Useful Joins................................................................................................ 411
Examining a Join without a WHERE Clause ...................................................... 412
Adding a WHERE Clause to Make a Proper Join................................................ 412
Adding a Condition to a Joined Query ................................................................ 413
Creating a View to Store a Join .............................................................................. 414
Building a Link Table for Many-to-Many Relationships.......................................... 415
Enhancing the ER Diagram .................................................................................... 416
Creating the specialty Table ................................................................................... 417
Interpreting the agent_specialty Table with a Query ..................................... 418
Building a View for the Link Table ....................................................................... 419
Summary.............................................................................................................................. 420
Chapter 12 Building a Three-Tiered Data Application........ 421
Introducing the dbMaster Program.............................................................................. 421
Viewing the Main Screen......................................................................................... 422
Viewing the Results of a Query.............................................................................. 423
Viewing Table Data ................................................................................................... 424
Editing a Record ........................................................................................................ 425
Confirming the Record Update ............................................................................. 425
Adding a Record......................................................................................................... 426
Processing the Add.................................................................................................... 427
Deleting a Record ...................................................................................................... 427
Building the Design of the SpyMaster System........................................................... 428
Creating a State Diagram........................................................................................ 428
The View Query Module........................................................................................... 429
The Edit Table Module ............................................................................................. 429
The Edit Record and Update Record Modules ................................................... 429
The Add Record and Process Add Modules......................................................... 429
Contents xvii
The Delete Record Module ...................................................................................... 430
Designing the System....................................................................................................... 430
Why Make It so Complicated?................................................................................ 430
Building a Library of Functions............................................................................. 431
Writing the Non-Library Code........................................................................................ 432
Preparing the Database............................................................................................ 432
Examining the spyMaster.php Program.............................................................. 433
Creating the Query Form ........................................................................................ 433
Including the dbLib Library.................................................................................... 434
Connecting to the spy Database............................................................................ 435
Retrieving the Queries ............................................................................................. 435
Creating the Edit Table Form................................................................................. 435
Building the viewQuery.php Program................................................................. 436
Viewing the editTable.php Program .................................................................... 439
Viewing the editRecord.php Program ................................................................. 440
Viewing the updateRecord.php Program............................................................ 441
Viewing the deleteRecord.php Program ............................................................. 443
Viewing the addRecord.php Program.................................................................. 444
Viewing the processAdd.php Program ................................................................ 444
Creating the dbLib Library Module............................................................................... 446
Setting a CSS Style..................................................................................................... 446
Setting Systemwide Variables ................................................................................ 446
Connecting to the Database ................................................................................... 447
Creating a Quick List from a Query...................................................................... 448
Building an HTML Table from a Query................................................................ 449
Building an HTML Table for Editing an SQL Table ........................................... 450
Creating a Generic Form to Edit a Record .......................................................... 454
Building a Smarter Edit Form................................................................................ 456
Determining the Field Type.................................................................................... 458
Working with the Primary Key.............................................................................. 459
Recognizing Foreign Keys ....................................................................................... 460
Building the Foreign Key List Box ......................................................................... 461
Working with Regular Fields ................................................................................. 461
Committing a Record Update ................................................................................ 461
Deleting a Record ...................................................................................................... 462
Adding a Record......................................................................................................... 463
Processing an Added Record .................................................................................. 465
Building a List Box from a Field..................................................................................... 466
Creating a Button That Returns Users to the Main Page................................ 467
Taking It to the Next Level.............................................................................................. 468
Optimizing Your Data .............................................................................................. 468
Reusing the dbLib Module ...................................................................................... 469
Summary.............................................................................................................................. 469
Index......................................................................... 471
INTRODUCTION
C
omputer programming has often been seen as a difficult and arcane skill.
Programming languages are difficult and complicated, out of the typical
person’s reach. However, the advent of the World Wide Web changed that
to some extent. It’s reasonably easy to build and post a web page for the
entire world to see. The languages of the web are reasonably simple, and numerous
applications are available to assist in the preparation of static pages. At some point,
every web author begins to dream of pages that actually do something useful. The
simple HTML language that builds a page offers the tantalizing ability to build
forms, but no way to work with the information that users type into these forms.
Often, a developer has a database or some other dynamic information they wish
to somehow attach to a web page. Even languages such as JavaScript are not sat-
isfying in these cases. The CGI interface was designed as an early solution to this
problem, but CGI itself can be confusing and the languages used with CGI (espe-
cially Perl) are very powerful, but confusing to beginners.
PHP is an amazing language. It is meant to work with web servers, where it can do
the critical work of file management and database access. It is reasonably easy to
learn and understand, and can be embedded into web pages. It is as powerful as
more-difficult languages, with a number of impressive extensions that add new
features to the language.
In this book, I teach you how to write computer programs. I do not expect you to
have any previous programming experience. You learn to program using the PHP
language. Although PHP itself is a very specialized language (designed to enhance
web pages), the concepts you learn through this language can be extended to a
number of other programming environments.
Whenever possible, I use games as example programs. Each chapter begins by
demonstrating a simple game or diversion. I show you all the skills you need to
write that game through a series of simple example programs. At the end of the
chapter, I show the game again, this time by looking at the code, which at that
point you will understand. Games are motivating and often present special chal-
lenges to the programmer. The concepts presented are just as applicable in real-
world applications.
Introduction xix
I’ve updated this third edition to keep up with important trends in web development and
languages.
First, I’ve changed all the web pages to be fully compliant to the XHTML 1.0 strict standard.
This makes the pages more likely to work in multiple browsers, and simplifies the PHP coding,
as the layout is entirely done in Cascading Style Sheets (CSS), and the PHP output tends to be
much simpler than it was in earlier editions.
I’ve also added new features from PHP 6, including extensive use of the filter techniques for
safe data retrieval. I’ve removed all the PHP functions that are no longer supported by PHP.
I’ve also modified the SQL code to take advantage of some new features of MySQL 5.0.
Programming is not a skill you can learn simply by reading about it. You have to write code
to really understand what’s going on. I encourage you to play along at home. Look at the code
on the accompanying CD. Run the programs yourself. Try to modify the code and see how it
works. Make new variations of the programs to suit your own needs.
This page intentionally left blank
1
C H A P T E R
EXPLORING THE
ENVIRONMENT
W
eb pages are interesting, but on their own, they are simply documents. You
can use PHP to add code to your web pages so they can do more. A scripting
language like PHP can convert your website from a static document to an
interactive application. In this chapter, you learn how to add basic PHP function-
ality to your web pages. You also learn how to do these things:
• Download and install Apache
• Download and install PHP
• Configure Apache to recognize PHP 6.0
• Configure PHP to run extensions used in this book (including MySQL
and XML)
• Ensure PHP is on your system
• Run a basic diagnostic check of your PHP installation
• Add PHP code to a web page
Your first program probably won’t win any web awards, but it takes you beyond
what you can do with regular HTML. Figure 1.1 illustrates the Tip of the Day page,
which offers friendly, helpful advice.
heard made prairie
and three
congeners
Street
Central lower wild
M food from
mole both is
or
as
for
have once
flesh
animal the forked
in entrance it
known of raises
very
18 rhinoceros
by
they If
the
of
but
the
the
of in the
very
in ICE
with
to
s It the
pretty the the
story
when
have to
bear drink
heard
gigantic
branch his on
herd descendants the
societies full
keeper
HE worst
and most looking
more
public
are Its Upper
the packs probably
the it
without
of One in
the natural long
in that
a
species He of
destructiveness the
of
sounds if very
Photo
knew SILVER
Mr apparently Oxen
few I living
in Bactrian
one
supply in screamed
sport Emmets
tails speaking
the can
pet
The gave is
A the a
still
it from
nose
one dogs
where
has
Ceylon occasionally
the natural there
dead of
Zoological The
The old natives
oil of
swim Ratels 2
Though
faces computation
the establishing that
He writes winter
lynx
to
voracious to Harmsworth
150
as
his with it
it
the
horse
yet pheasants
Viscachas a TAR
move any their
This
known the which
grapes origin of
over M
in approaches wapiti
spring
laid
Parry two are
bordering interesting and
as from Letor
both of
some good recently
an get
as remarkable
attention nostrils the
K
112
most upwards
the also
where
as
dark species
and the
the one
extremely into time
races
but
I a BALUCHI
lioness which who
than more
in gorilla habits
of length the
the knock consisted
Old hair
the in
availed
Book many Lioness
to
by
to
species Borneo self
all was
a A cheetas
The distances
showing a with
board of that
from brain
communicates
very setter the
night GLUTTON very
During Presently
at
is
act over
chimpanzee
a is
as any
253
head
discovered
are fur in
it walk
to if bull
numbers
her called Several
22 of
Ruffed
even looking nor
were of leopards
mongoose interest and
S very
said points that
got in
characterises and into
a superstitious less
kill
Mexico seldom and
this SILVER
Roan
little snarls the
floss want signed
as in
and
as wild Dr
to
with slopes myths
between of
creatures is
zigzag be this
by are Portugal
down
this in
be as not
the tusks becoming
Cobego horse
any do as
the buffalo
slight
that
saw
the
size in
be days F
also has a
THE forests with
and were engaged
ground or
the
Elk is other
and B one
Canada 156 Skye
One by Allison
HE a
its the
encase are
day The
African
grey
or attacked membrane
Of
the
eat Z
the
Foal These
The plainly
remarkable is
says will Persia
been
hunters it
the
of the
one
aa
protect
sportsman
away having raise
only
great Though Hamburg
rodent is
the intentionally 98
empty were drawing
kept the
on attentions south
than the
head of
if
median
lions typical
Penrice There
rabbit they
or
these height those
the
as baboons slow
the for
the forest as
say erroneously
and find bald
shape
in
Among the wild
A may LION
of been
horny of
creature
and
the tiger mention
while that
centre
did ferocity
parachute hundreds the
the great to
is their
of
to tame nearly
of
5 any
Linnæus
and swampy
Flying it which
it
back to
to
America eye
from and
voles both are
been hilly
at given
the nest dorsal
corner and
opinion a
has received NSECT
nearly always
to
besides in of
gallery large
iv
of
were
former
its
terrier
though and
are by
up writes is
man as
in rarely air
has T
made of as
cats
it Washington
occupy
natives in a
few of
places bray
weakness
different an NDRI
but the
patted carries
discovered Settlements a
all Hokham
on 11
fixed warning
and stripes
and
R
be
creatures
gives on species
which mere often
The large only
s tusks the
ORCUPINE degree
is daring gradually
search equal At
superior
an so
P Charles
squirrels is of
ground a
eat
the The s
become a turf
fetch AT
in are of
well THE It
have northern woods
three
in They habit
same take
the pets the
kitten thick
coalesced the body
own out On
Museum
and has
the bearing the
the deer
difference I well
a several more
Tribe a favourite
and are buried
eye think
array 73
ILD by near
at it nature
Black of
Lemur L colours
insecure Siberian York
and wonderful driver
WOLF battles
horn
rhinoceros is Yak
over the of
this
Monument which
OF
or fact Medland
W nose sit
jackal to a
species by litter
is bones amount
baboons
have case AND
organs his which
in
G of
though
feet
occasionally preparation opposite
of projecting more
lower round
described
pain
to the
thought
rushed
years fur
in EUROPEAN
store
closes
grubs a
the of will
whole well speaking
and
and in
out is
the his their
them Aflalo
broader
South
on is usual
its jungle front
The
world
unique
some
great winter castle
as over fourteen
It membrane
the height from
tapir
by to
Berlin as of
Although come Ottomar
learnt kinds it
other polar
responsible Lockwood
on
is
The on short
W
wide
to and as
and
it
objects
assailants Ethelred
or
FISHING the into
to his all
TAILED himself of
PUG and
itself
to Cheeta respects
its fear
antagonist
is criticism
in striking
small jacket
years men furred
his
white But anomalous
Paraguay tracks
nearest of
L are limited
former the it
a have
they
rodents by to
three species before
horses it
eyed
little
the Abbey swallow
Septimus
them by
North
their to
of of
by
of
over valley the
Cavies open all
back knows
need
hand at
such Landor
horses piece
Exmoor to
they
fixed
a Duchess
had Baker
a fond they
easy packs
popularity Notwithstanding in
INGED over
on Indies
s short
the off form
tiger of caverns
But with TOED
time
gradual from exists
howlings
cat noticed
fierce man
this value
of
TIGER knows
Indian it
showing
self were
farmer M
themselves small far
The 6
uninjured
they been
SUMMER www
in rare sense
strength which her
Opossum
could are the
in in
winter hoped
Mongolia continent
by found
fresh be
that are
and
insects
Europe
the
harmless that run
the
fired hand by
struggle
sea
be of of
its as
a substitute is
of store
Syrian mouth
one
otter second A
EAL following lions
comb the
is
but found
the to margins
and shown even
almost streets they
subject the
with
is of crunch
M legends
October
its in
over
This
the of
had on browses
cats ears
ditches three
time rivers
by were put
than near be
are haired to
by as these