Testing Your MySQL Installation In this section, you will start and work with the MySQL utilities via thecommand line in a console window.. At this prompt mysql> you will type commands u
Trang 1The Premier Press logo, top edge printing, and related trade dress aretrademarks of Premier Press, Inc and may not be used without
Trang 2Indexer: Johnna VanHoose Dinse
PHP is copyrighted by The PHP Group, and is released under thePHP License More information on the licensing terms is available inthe license file within the PHP distribution or by visiting
http://www.php.net/license/ Microsoft, Windows, and Internet Explorerare either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries Netscape is aregistered trademark of Netscape Communications Corporation in theU.S and other countries
contained in this book has been obtained by Premier Press from
sources believed to be reliable However, because of the possibility ofhuman or mechanical error by our sources, Premier Press, or others,the Publisher does not guarantee the accuracy, adequacy, or
completeness of any information and is not responsible for any errors
or omissions or the results obtained from use of such information.Readers should be particularly aware of the fact that the Internet is anever-changing entity Some facts may have changed since this bookwent to press
ISBN: 1-931841-87-X
Library of Congress Catalog Card Number: 2002104489
Printed in the United States of America
02 03 04 05 RI 10 9 8 7 6 5 4 3 2 1
Trang 3Thanks as always to the PHP Group, Zend Technologies, the ApacheSoftware Foundation, and MySQL AB for creating and maintainingsuch wonderful and accessible products for all users
About the Author
JULIE MELONI is the technical director for i2i Interactive, a
multimedia company located in Campbell, CA (that's just down thestreet from San Jose) She's been developing Web-based
applications since the Web first saw the light of day and remembersthe excitement surrounding the first GUI Web browser She is theauthor of several books and articles on Web-based programminglanguages and database topics, and you can find translations of herwork in several languages, including Chinese, Italian, Portuguese,Polish, and even Serbian
Trang 4
PHP Fast & Easy Web Development, 2nd Edition
by Julie C Meloni ISBN:193184187x
Premier Press © 2002 (481 pages)
Getting Web developers up to speed with PHP.
Table of Contents Back Cover
Trang 6PHP Fast & Easy Web Development, 2nd Edition
by Julie C Meloni ISBN:193184187x
Premier Press © 2002 (481 pages)
Getting Web developers up to speed with PHP.
Table of Contents Back Cover
Back Cover
Don’t spend your time wading through manuals to
learn PHP Spend it doing what you do best—creating Web pages! Get the skills you need to install PHP,
Screen by screen, use this comprehensive PHP guide to:
Trang 7a multimedia company located in Campbell, CA She’s 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
is the author of several books and articles on Web-based programming languages and database topics.
Trang 8
running
A few additional chapters have been added to provide additional
projects for practicing your new-found skills; and some appendices ofadditional database and programming information also round out thisnew edition This book remains a solid introduction for the beginninguser, who learns best by example After completing this book, you willhave a strong foundation in the basics before approaching advancedlevels of application design
Before jumping into all that, take a moment to familiarize yourself withPHP and its history
Trang 9side scripting language When your Web browser accesses a URL, it
Its official name is PHP: Hypertext Preprocessor, and it is a server-is making a request to a Web server When you request a PHP page,something like http://www.yourcompany.com/home.php, the Web
server wakes up the PHP parsing engine and says, "Hey! You've got
to do something before I send a result back to this person's Web
browser."
Then, the PHP parsing engine runs through the PHP code found inhome.php, and returns the resulting output This output is passedback to the Web server as part of the HTML code in the document,which in turn is passed on to your browser, which displays it to you
A Brief History of PHP
In 1994, an incredibly forward-thinking man named Rasmus Lerdorfdeveloped a set of tools that used a parsing engine to interpret a fewmacros here and there They were not extravagant: a guest book, acounter, and some other "home page" elements that were cool whenthe Web was in its infancy He eventually combined these tools with aform interpretation (FI) package he had written, added some databasesupport, and released what was known as PHP/FI
Then, in the spirit of Open Source software development, developersall over the world began contributing to PHP/FI By 1997, more than50,000 Web sites were using PHP/FI to accomplish different tasks—connecting to a database, displaying dynamic content, and so on
At that point, the development process really started becoming a teameffort With primary assistance from developers Zeev Suraski andAndi Gutmans, the version 3.0 parser was created The final release
of PHP 3.0 occurred in June of 1998, when it was upgraded to includesupport for multiple platforms (it's not just for Linux anymore!) andWeb servers, numerous databases, and SNMP (Simple Network
Trang 10Protocol)
Then, the birth of PHP 4.0 occurred No small version change, PHP4.0 marked a complete rethinking of the PHP core and a rewrite of theinternals of the scripting language itself The PHP development teamand Zend Technologies produced a remarkable product with nearly a50-fold performance improvement over version 3.0, with a long list ofnew and useful features
So where are we now?
Over 7 million Web servers worldwide run the 4.x version ofPHP
PHP 4.x has been in use for over two years, with the currentversion being 4.2.1
PHP 4.x can work with just about any combination of Webserver, operating system, and database you can think up.Companies such as Zend Technologies have released
products to optimize and accelerate PHP, as well as "studio"environments for developing and testing PHP code
PHP usage has exploded as an enterprise application
development solution—it's not just for home pages and smallprojects any more!
What Does PHP Do?
PHP does anything you want, except sit on its head and spin Actually,with a little on-the-fly image manipulation and Dynamic HTML, it couldprobably do that, too
According to the PHP manual, "The goal of the language is to allowWeb developers to write dynamically generated pages quickly."
Here are some common uses of PHP:
Trang 11Gather data from forms: save the data to a file, send data viae-mail, return manipulated data to the user
Access databases and generate content on-the-fly, or create aWeb interface for adding, deleting, and modifying elementswithin your database
Set cookies and access cookie variables
Start sessions and use session variables and objects
Use PHP user authentication to restrict access to sections ofyour Web site
Create images on-the-fly
Encrypt data
These are just everyday uses PHP includes support for Java, JavaServlets, XML, and a myriad of other higher-level functions The
possibilities are endless
Trang 12
Only you can decide if PHP should be your language of choice,
whether you're developing sites for personal or commercial use on asmall or large scale I can only tell you that in the commercial realm,I've worked with all the popular server-side scripting languages—Active Server Pages (ASP), ColdFusion, Java Server Pages (JSP),Perl, and PHP—on numerous platforms and various Web servers,with varying degrees of success PHP is the right choice for me: it'sflexible, fast, and simple in its requirements, yet powerful in its output.Before deciding whether to use PHP in a large-scale or commercialenvironment, consider your answers to these questions:
Can you say with absolute certainty that you will always usethe same Web server hardware and software? If not, look forsomething cross-platform that is available for all types of Webservers: PHP
Will you always have the exact same development team
comprised entirely of ASP (or ColdFusion) developers? Or willyou use whoever is available, thus necessitating a languagethat is easy to learn and syntactically similar to C and Perl? Ifyou have reason to believe that your ASP or ColdFusion
developers might drop off the face of the earth, don't use
those tools—use PHP
Are memory and server load an issue? If so, don't use bloatedthird-party software that leaks precious memory—use PHP.Here's the bottom line: PHP is simple, so just try it! If you like it,
continue using it It's Open Source, so help improve it Join a mailinglist, and help others If you don't like it, you're only out about 25 bucksfor this book, and the software can be uninstalled without renderingyour machine completely inoperable
Trang 14
This book has its own Web site That figures, doesn't it? The URL ishttp://www.premierpressbooks.com/downloads.asp At this site youcan download all the code samples in this book You can also use thissite to alert me to bugs or other problems you might have with theexamples Although the code has been tested many times, one errantsemicolon or quotation mark can cause the dreaded "Parse error."
Trang 15
Part I: Getting Started
Trang 17Chapter 1: Installing and Configuring MySQL
Trang 18MySQL is the database of choice for a vast majority of Web
developers who use PHP because of its efficiency and ease of use.Plus, MySQL is free, runs on multiple platforms, and its
documentation is superb When using MySQL with PHP, it's easiest toinstall MySQL first because, during the PHP installation and
configuration process, you must tell the PHP configuration script
specific functions In this chapter, you'll learn how to do the following:
where MySQL resides on your system in order to activate the MySQL-Install MySQL on Windows or Linux
Create a sample database
Create a sample table
Trang 19
The most popular distribution of MySQL is the open source versionfrom MySQL AB However, there are also commercial versions ofMySQL, as well as distributions of MySQL bundled with applicationserver software Some companies that offer these options are
AbriaSoft (http://www.abriasoft.com/) and NuSphere
(http://www.nusphere.com/) No matter which option you choose, asolution will be available for you on all platforms-any UNIX-like
operating system, as well as on Windows 95/98/NT/2000/XP
If you are using MySQL as part of a Web hosting package through anInternet service provider, you don't have to worry about downloadingand installing the application in this chapter Instead, you'll just need
to work with your ISP to get your username and password In almostall cases, your ISP will be running the MySQL distribution from
MySQL AB There's no harm in setting up MySQL on a developmentmachine, if you have one available to you (your own workstation fitsthat bill), just to better understand the process To that end, if you
have a Linux workstation or server, MySQL was likely included onyour OS distribution CDs as an installation option, and perhaps youeven installed it already In this case, you should check the MySQLWeb site to compare the version numbers and download a newerversion if one is available
The installation instructions in this chapter are based on the MySQLversion 4.0, distributed by MySQL AB Earlier versions such as
MySQL 3.23.x follow the same steps, should you run into problemswhile installing MySQL 4.0 You will be able to use all of the database-related examples in this book, whether using MySQL 3.23.x or MySQL4.0
Trang 20
The MySQL installation process on Windows 95/98/NT/2000/XP isbased on an executable setup program provided by MySQL AB Onceyou download the zip file, all you have to do is extract its contents into
a temporary directory and run the setup.exe application After thesetup.exe application installs the MySQL server and client
programs, you're ready to start the MySQL server
1 Visit the MySQL 4.0 download page, at
http://www.mysql.com/downloads/mysql-4.0.html and findthe Windows section on the page You want to download the
"Installation files (zip)" rather than "Cygwin downloads
(tar.bz2)."
2 Clicking the Download link will take you to a page of mirrorsites Select the mirror site closest to you, and click on eitherthe HTTP or FTP link to download the file Using the HTTPmethod is usually quicker
3 Once the Zip file is on your hard drive, extract its contents to
a temporary directory
4 From the temporary directory, find the setup.exe file anddouble-click it to start the installation You will see the firstscreen of the installation wizard Click Next to continue
Trang 215 The second screen in the installation process contains
valuable information regarding the installation location Thedefault installation location is C:\mysql, but if you plan toinstall MySQL in a different location, this screen shows you afew changes that you will have to make on your own Theinformation on this screen is also important for Windows NTusers who wish to start MySQL as a service Read the
information and note anything relevant to your situation, thenclick Next to continue
6 With the third screen in the installation process, you willselect the installation location If you want to install MySQL
in the default location, click Next to continue Otherwise,click Browse and navigate to the location of your choice,then click Next to continue
Trang 227 The fourth screen has you select the installation method,either Typical, Compact, or Custom Select Typical, and clickNext to continue.
8 The installation process will now take over, and install files intheir proper locations When the process is finished, you willsee a confirmation of completion Click Finish to completethe setup process
Trang 23WinMySQLadmin will automatically interpret environmentinformation, such as IP address, machine name, and so on.The tabs across the top allow you to view system
information and also edit MySQL configuration options Toshut down the MySQL server and/or the WinMySQLadmintool, right-click again on the Stoplight icon in your taskbarand select the appropriate choice As long as the MySQLserver is running, you can run additional applications
through a console window, such as the MySQL monitor
In the next section, you'll learn how to manually start MySQLand perform a few actions to familiarize yourself with thesystem
Testing Your MySQL Installation
In this section, you will start and work with the MySQL utilities via thecommand line in a console window When using MySQL with PHP,
Trang 24yourself with the types of commands and responses you'll be workingwith later in the book
Starting MySQL
To manually start MySQL, follow the steps below
1 Open a DOS prompt or a console window (depending onyour Windows version, it may be called one or the other)
2 At the prompt, type cd c:\mysql\bin and press Enter.
Note If you installed MySQL in a different directory,
substitute that directory name in the command instep 2
3 At the prompt, type mysqld-opt and press Enter.
The MySQL process will now be running in the background.You can now connect to MySQL and create databases andtables
Creating a Test Database
Before going any further, you should know the following:
A database is a collection of tables
Trang 25Each field categorizes a piece of a data
In this section, you'll conquer the first element and create a database.The utility to use is the mysqladmin program, which allows you toadminister MySQL from the command line
command line
1 At the prompt, type mysql and press Enter.
Trang 26At this prompt (mysql>) you will type commands used tocreate tables, explain tables, insert data, select data, and so
on Get used to ending your commands with a semicolon (;)because it's a common instruction terminator that is used inPHP as well
Note For more information about the specifics of
Trang 27creating tables, see Appendix D, "Basic MySQLReference."
Trang 285 To verify the field names and types in a specific table, use
the explain command In this case, type explain test_table;
and press Enter
The MySQL Monitor will respond with a list of all the fieldsand their types in the selected table This is a very handycommand to use to keep track of your table design
It's time to insert a few rows of data in your table, becausethis is getting pretty boring The first row will have an ID of 1,and the note will be "This is a note."
6 To insert this row, type insert into test_table values('1',
'This is a note.'); and press Enter.
The MySQL Monitor will respond with Query OK It will alsotell you how many rows were affected and how long it took
to complete the task
Trang 297 Insert another row by typing insert into test_table
values('99', 'Look! Another note.'); and pressing Enter.
Note For more information about the specifics of
inserting data into tables, see Appendix D, "BasicMySQL Reference."
Now that you have some data in your table, even if it is onlytwo rows, get familiar with selecting data Keep the MySQLMonitor open because you'll be using it in the next section
as well
Selecting Data from Your Test Table
The SELECT command is very powerful and will likely be the
command you use most often when working with PHP and MySQL.You can find more information about the SELECT command in
Appendix D, "Basic MySQL Reference," but for now, let's do somesimple data selections
1 At the prompt, type select * from test_table; and press
Enter
This command simply selects all fields from all rows (that'swhat the * does) in the table called test_table and returnsthe data to the screen in a nicely formatted table The
MySQL Monitor tells you how many rows were returned andhow long it took the query to run
Trang 30Chapter 2, "Installing Apache," to install the Apache Webserver
Trang 32
3 At the prompt, type cd /usr/local
Note You can install MySQL in any directory If you do
not use /usr/local/ as in the example above,
be sure to modify subsequent commandsappropriately
of the MySQL manual, which is located at
http://www.mysql.com/doc/P/r/Problems.html Some common
problems include
Trang 33instructions
If you see the message "Access denied" when connecting toMySQL, be sure you are using the correct username andpassword
If you see the message "Can't connect to server," make surethe MySQL daemon is running
In the next section, you'll learn how to start MySQL and perform a fewactions to familiarize yourself with the system
Testing Your MySQL Installation
In this section, you will start and work with the MySQL utilities via thecommand line, in a console window When using MySQL with PHP,you'll issue the same types of commands, only within the context ofthe PHP code Use the information in this section to familiarize
yourself with the types of commands and responses you'll be workingwith later in the book
Creating a Test Database
Before going any further, you should know the following:
Trang 34A table contains a set of records, also referred to as rows.All records have the same number of fields
Each field categorizes a piece of a data
In this section, you'll conquer the first element and create a database.The utility to use is the mysqladmin program, which allows you toadminister MySQL from the command line
1 At the prompt, type /bin/mysqladmin create testDB and
press Enter
As you can see by the system response, a database calledtestDB has been created Next, you'll add a table to thatdatabase
Creating a Test Table
In this section, you'll create a table within the database you created inthe preceding section The utility to use is the mysql program, whichallows you to work within the MySQL database system from the
command line
1 At the prompt, type /bin/mysql and press Enter.
Trang 35commands used to create tables, explain tables, insert data,select data, and so on Get used to ending your commandswith a semicolon (;) because it's a common instruction
Note For more information about the specifics of
creating tables, see Appendix D, "Basic MySQLReference."
Trang 36to complete the task (in this case, 0.03 seconds)
4 Verify the table creation by typing show tables; and
pressing Enter
The MySQL Monitor will respond with a list of all tables inthe current database
5 To verify the field names and types in a specific table, use
the explain command In this case, type explain test table;
and press Enter
Trang 37It's time to insert a few rows of data in your table becausethis is getting pretty boring The first row will have an ID of 1,and the note will be "This is a note."
6 To insert this row, type insert into test table values('1',
'This is a note.'); and press Enter.
The MySQL Monitor will respond with Query OK It will alsotell you how many rows were affected and how long it took
Trang 38as well
Selecting Data from Your Test Table
The SELECT command is very powerful and will likely be the
command you use most often when working with PHP and MySQL.You can find more information about SELECT in Appendix D, "BasicMySQL Reference," but for now, we'll do some simple data selections
1 At the prompt, type select * from test_table; and press
Enter
This command simply selects all fields from all rows (that'swhat the * does) in the table called test_table and returnsthe data to the screen in a nicely formatted table The
MySQL Monitor tells you how many rows were returned andhow long it took the query to run
Add a little order to the results Try to get the results ordered
by ID number—largest number first
2 At the prompt, type select * from test_table order by
test_id desc; and press Enter.
Trang 39In the next chapter, you'll install the Apache Web server and
be one step closer to developing dynamic, database-drivenWeb sites!
Trang 40
Chapter 2: Installing Apache