MySQL ™TM ® From & Your visual blueprint™ to open source database management by Michael Moncur... Library of Congress Control Number: 2002110260 ISBN: 0-7645-1692-2 Manufactured in the U
Trang 1MySQL ™
TM
®
From
&
Your visual blueprint™ to open source database management
by Michael Moncur
Trang 2Published by
Wiley Publishing, Inc.
909 Third Avenue
New York, NY 10022
Published simultaneously in Canada
Copyright © 2003 Wiley Publishing, Inc., Indianapolis, Indiana
Certain designs and text Copyright © 1992-2003 maranGraphics, Inc., used with
maranGraphics' permission.
maranGraphics, Inc.
5755 Coopers Avenue
Mississauga, Ontario, Canada
L4Z 1R9
No part of this publication may be reproduced, stored in a retrieval system or
transmitted in any form or by any means, electronic, mechanical, photocopying,
recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission
of the Publisher, or authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,
(978) 750-8400, fax (978) 750-4744 Requests to the Publisher for permission
should be addressed to the Legal Department, Wiley Publishing, Inc., 10475
Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447,
E-mail: permcoordinator@wiley.com.
Library of Congress Control Number: 2002110260
ISBN: 0-7645-1692-2
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1V/SR/RQ/QS/IN
Trademark Acknowledgments
Wiley, the Wiley Publishing logo, Visual, the Visual logo,
Simplified, Master VISUALLY, Teach Yourself VISUALLY, Visual
Blueprint, In an Instant, Read Less – Learn More and related
trade dress are trademarks or registered trademarks of Wiley
Publishing, Inc in the United States and other countries and
may not be used without written permission The maranGraphics
logo is a trademark or registered trademark of maranGraphics,
Inc MySQL is a trademark or registered trademark of MySQL AB
Company All other trademarks are the property of their
respective owners Wiley Publishing, Inc and maranGraphics,
Inc are not associated with any product or vendor mentioned in
this book
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE
PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN
WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS
OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE
ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE
FOR YOUR SITUATION YOU SHOULD CONSULT WITH A PROFESSIONAL
BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL
DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL,
Permissions
FOR PURPOSES OF ILLUSTRATING THE CONCEPTS AND TECHNIQUES DESCRIBED IN THIS BOOK, THE AUTHOR HAS CREATED VARIOUS NAMES, COMPANY NAMES, MAILING, E-MAIL AND INTERNET
ADDRESSES, PHONE AND FAX NUMBERS AND SIMILAR INFORMATION, ALL OF WHICH ARE FICTITIOUS ANY RESEMBLANCE OF THESE FICTITIOUS NAMES, ADDRESSES, PHONE AND FAX NUMBERS AND SIMILAR INFORMATION TO ANY ACTUAL PERSON, COMPANY AND/OR ORGANIZATION IS UNINTENTIONAL AND PURELY COINCIDENTAL
Important Numbers
For U.S corporate orders, please call maranGraphics at 800-469-6616 or fax 905-890-9434
For general information on our other products and services
or to obtain technical support, please contact our Customer Care Department within the U.S at 800-762-2974, outside the U.S at 317-572-3993, or fax 317-572-4002
maranGraphics Certain text and illustrations by maranGraphics, Inc., used with maranGraphics' permission.
MySQLTM: Your visual blueprintTMto open source
database management
U.S Trade Sales Contact Wiley
at (800) 762-2974
or fax (317) 572-4002.
U.S Corporate Sales Contact maranGraphics
at (800) 469-6616 or fax (905) 890-9434.
is a trademark of Wiley Publishing, Inc.
Was it a monument? A temple? Perhaps the giant Pyramid of Kukulkán, called El Castillo by Spanish visitors to the ancient Mayan city of Chichén-Itzá, was both, and more Built with mathematical precision, it dominates the city from every direction, and is among the most recognized ancient landmarks Explore the mysteries of Chichén-Itzá in
Frommer's Cancún, Cozumel and the Yucatán, available wherever books
are sold or at www.frommers.com.
Trang 3MySQL TM
Your visual blueprintTM to open source database management
Trang 4At maranGraphics, we believe in producing great
computer books — one book at a time
maranGraphics has been producing high-technology
products for over 25 years, which enables us to offer the
computer book community a unique communication
process
Our computer books use an integrated communication
process, which is very different from the approach used
in other computer books Each spread is, in essence, a
flow chart — the text and screen shots are totally
incorporated into the layout of the spread Introductory
text and helpful tips complete the learning experience
maranGraphics' approach encourages the left and right
sides of the brain to work together — resulting in faster
orientation and greater memory retention
Above all, we are very proud of the handcrafted nature
of our books Our carefully-chosen writers are experts
in their fields, and spend countless hours researching
and organizing the content for each topic Our artists
rebuild every screen shot to provide the best clarity possible, making our screen shots the most precise and easiest to read in the industry We strive for perfection, and believe that the time spent handcrafting each element results in the best computer books money can buy
Thank you for purchasing this book We hope you enjoy it!
Sincerely,
Robert Maran
President
maranGraphics Rob@maran.com www.maran.com
maranGraphics is a family-run business located near Toronto, Canada.
Trang 5Wiley Technology Publishing Group: Richard Swadley, Vice President and Executive Group Publisher;
Bob Ipsen, Vice President and Executive Publisher; Barry Pruett, Vice President and Publisher; Joseph Wikert, Vice President and Publisher; Mary Bednarek, Editorial Director; Mary C Corder, Editorial Director;
Andy Cummings, Editorial Director
Wiley Production for Branded Press: Debbie Stailey, Production Director
Acquisitions, Editorial, and Media Development
Project Editor
Sarah Hellert
Acquisitions Editor
Jen Dorsey
Product Development Supervisor
Lindsay Sandman
Copy Editor
Jill Mazurczyk
Technical Editor
Scott Hofmann
Editorial Manager
Rev Mengle
Permissions Editor
Carmen Krikorian
Media Development Specialist
Megan Decraene
Manufacturing
Allan Conley Linda Cook Paul Gilchrist Jennifer Guynn
Production
Book Design
maranGraphics®
Production Coordinator
Nancee Reeves
Layout
Beth Brooks Melanie DesJardins Carrie Foster LeAndra Johnson Kristin McMullan Heather Pope Erin Zeltner
Screen Artists
Jill A Proll
Cover Illustration
David E Gregory
Proofreader
Laura L Bowman
Quality Control
John Bitter Dave Faust John Greenough Angel Perez Dwight Ramsey
Indexer
Liz Cunningham
Special Help
Cricket A Krengel
CREDITS
ACKNOWLEDGMENTS
Trang 6Michael Moncur is the author of many books on system administration and Web development topics.
He has recently written books about JavaScript and DHTML He works as an independent network consultant and Web programmer
Michael also manages and maintains several popular Web sites His oldest and most popular site, The Quotations Page, has been online since 1994 Most of the site's content is stored in a MySQL database, and presented using PHP Michael lives with his wife, Laura, in a suburb of Salt Lake City, Utah
I am continually amazed at how complicated it is to write and publish a computer book Fortunately, a great deal of this complexity was handled smoothly by the team at Wiley This began with Jen Dorsey, the acquisitions editor, who was instrumental in getting the project started and keeping it running smoothly The project editor, Sarah Hellert, communicated with me constantly, managed every detail of the production, and helped me figure out the intricacies of the visual format I have grown to love The copy editor, Jill Mazurczyk, saved me from many embarrassing errors and kept the style consistent The technical editor, Scott Hofmann, painstakingly tested all of the examples, helped me avoid technical errors, and made some valuable suggestions about content and coverage Thanks are also due to the many people in the graphics and production departments who handled the final details
I'd also like to thank Neil Salkind at Studio B, for his help in getting this project lined up and keeping it going, and David and Sherry Rogelberg, Jessica Richards, and the rest of the team at Studio B Finally, thanks to my wife, Laura, and the rest of my friends and family
ABOUT THE AUTHOR
AUTHOR'S ACKNOWLEDGMENTS
Trang 7Dedicated to my wife, Laura, my parents, and everyone else who sees less of me while I'm busy writing.
Trang 8HOW TO USE THIS BOOK XIV 1) INTRODUCING MYSQL
Understanding MySQL .2
MySQL Terminology .4
Other Database Systems .5
Structured Query Language (SQL) .6
Download MySQL .8
Install MySQL under Linux from a Package 10
Install MySQL under UNIX from Source .12
Install MySQL under Windows .14
Start the MySQL Server .16
Test the MySQL Installation 17
Using the MySQL Monitor .18
View the Server Status .20
Try an SQL Query .21
Configure a MySQL User .22
Specify a Multiple-Line Query .24
Edit a Long Command .26
Configure MySQLGUI .28
2) MANAGE DATABASES AND TABLES Design a Database .30
Create and Drop Databases .32
Create a Database 33
Show Available Databases .34
Select a Database .35
Create and Drop Tables .36
Create a Simple Table 38
Show Table Information .40
Numeric Column Types .42
Text and Date Column Types 44
Using Text Columns .46
Using Sets and Enumerations .48
Create an Indexed Table .50
Delete Tables and Databases 52
TABLE OF CONTENTS
Trang 93) MODIFY TABLES
Using ALTER TABLE Queries 54
Add a Column to a Table .56
Add an Index .58
Add a Primary Key or Unique Index .60
Add a Timestamp Column .62
Add an Auto-Increment Column .64
Rename a Column .66
Change a Column Type .68
Delete a Column 70
Delete an Index or Primary Key .72
Rename a Table .74
Change a Table Type 75
4) ADD AND DELETE DATA Using INSERT and DELETE Queries 76
Add a Row to a Table .78
Specify Columns for a New Row .80
Specify Insert Priority .81
Using Auto-Increment Columns .82
Using Timestamp Columns .84
Replace an Existing Row 86
Insert Rows from Another Table .88
Delete a Specific Row .90
Delete All Table Rows 92
Limit the Number of Deleted Rows .93
Delete Data by Date 94
5) UPDATE DATA IN TABLES Using UPDATE Queries 96
Modify a Single Row 98
Modify Multiple Rows .100
Update All Table Rows .102
ix
BOOK TITLE:
Your visual blueprint forthest
of the book title
MYSQL:
Your visual blueprint to open source database management
Trang 10Limit the Number of Rows to Update .103
Update Multiple Columns .104
Update Depending on Column Values 106
Increment a Column Value .108
6) USING SELECT QUERIES Using SELECT Queries .110
Display Data with SELECT .112
Using the WHERE Clause .114
Specify Multiple WHERE Conditions .116
Using the LIMIT Clause .118
Sort Data with the ORDER BY Clause .120
Using the GROUP BY Clause .122
Using Multiple Clauses with SELECT .123
Count Database Rows .124
Calculate Totals and Averages .126
Display Data from Multiple Tables .128
Using JOIN Options .130
Display Data with MySQLGUI .132
7) USING MYSQL FUNCTIONS Math Functions .134
Using Math Functions 136
Compare Numeric Values .138
Understanding String Functions .140
Compare String Values .142
Using String Functions .144
Work with Substrings .146
Understanding Date and Time Functions .148
Work with Dates and Times .150
Display Formatted Dates .152
Add and Subtract Dates and Times .153
Miscellaneous Functions .154
TABLE OF CONTENTS
Trang 118) IMPORT AND EXPORT DATA
Import and Export Tools .156
Export to a Text File with SELECT .158
Format an Import File 160
Import from a Text File 162
Export Data from a Spreadsheet 164
Export Data from Microsoft Access .166
Back up Data from a Table 168
Restore a Backup File .169
Manage Automated Backups .170
Back up Table Structure .172
Create a Copy of a Table .173
9) MANAGE THE MYSQL SERVER MySQL Administration Tools .174
Check Server Status .176
Check the MySQL Server Version 177
Start and Stop the MySQL Server under UNIX .178
Start and Stop the MySQL Server Under Windows .180
View and Manage Running Processes .182
Using WinMySQLadmin .184
Manage MySQL with MySQLGUI .186
10) OPTIMIZE AND TROUBLESHOOT MYSQL Optimize MySQL .188
Check a Table for Errors 190
Optimize and Repair Tables 192
MySQL Configuration Options .194
Display Server Performance Information 196
Edit the Configuration File in UNIX .198
Edit the Configuration File in Windows .199
xi
MYSQL:
Your visual blueprint to open source database management
Trang 12TABLE OF CONTENTS
View MySQL Log Files .200
Improve Performance with Indexes .202
Manage Table Locking .204
11) CONFIGURE MYSQL SECURITY The Importance of Security .206
MySQL Security Basics .207
Grant Privileges to Users .208
Modify User Passwords .210
View a User's Privileges .212
View Security Tables 214
Control Network Access .216
Advanced MySQL Security .217
12) USING MYSQL WITH PHP Introducing PHP .218
Test the PHP Installation .220
Install and Test phpMyAdmin .222
Manage Data with phpMyAdmin .224
Manage the MySQL Server with phpMyAdmin 226
Connect to a MySQL Server .228
Display Query Results .230
Store Query Results as Objects 232
Insert a Record from PHP .234
Delete Records Using PHP 236
Create a Form to Add Records .238
Create a Database Search Form .240
13) USING MYSQL WITH PERL Introducing Perl 242
Install Perl under UNIX 244
Install Perl under Windows .246
Trang 13MYSQL:
Your visual blueprint to open source database management
Install the Perl DBI .248
Install the MySQL DBD .249
Connect to a MySQL Server .250
Display Query Results .252
Insert a Record from Perl .254
Delete Records Using Perl .255
Work with Web Forms .256
APPENDIX A Glossary 258
APPENDIX B Create and Delete Tables and Databases 260
Modify Tables with ALTER TABLE .262
Add and Delete Data .263
Modify Existing Data with UPDATE 264
Retrieve Data with SELECT .265
Display Status Information .266
Administrative Commands 267
Command-Line Utilities .268
APPENDIX C What's on the CD-ROM 270
Using the E-Version of this Book 272
Wiley Publishing Inc End User License Agreement 274
GNU General Public License 276
INDEX 280
Trang 14HOW TO USE THIS BOOK
MySQL: Your visual blueprint to open source database
management uses simple, straightforward examples to
teach you how to create powerful and dynamic programs
To get the most out of this book, you should read each
chapter in order, from beginning to end Each chapter
introduces new ideas and builds on the knowledge
learned in previous chapters When you become familiar
with MySQL: Your visual blueprint to open source database
management, you can use this book as an informative
desktop reference
Who This Book Is For
If you are interested in creating databases, applications,
and data-driven Web sites using MySQL, MySQL: Your
visual blueprint to open source database management is
the book for you
This book introduces you to the SQL language that
forms the foundation of MySQL as well as the specific
commands, utilities, and features unique to MySQL It
also covers the use of MySQL with the popular PHP and
Perl languages for creating dynamic, database-backed Web
pages
Although this book requires no prior experience with
databases or SQL, a basic familiarity with either Windows
or UNIX servers is an asset
What You Need to Use This Book
To perform the tasks in this book, you need a computer to
run the MySQL server This can be either a machine
running Windows 98, ME, NT, 2000, or XP; or a machine
running a UNIX-based operating system such as Linux
The MySQL server software is available at no charge, and
installing it on your system is detailed in Chapter 1
The Conventions in This Book
A number of typographic and layout styles have been used
throughout MySQL: Your visual blueprint to open source database management to distinguish different types of
information
Courier Font
Indicates the use of MySQL commands, command-line utilities, HTML tags and attributes, and commands in PHP
or Perl
Bold
Indicates information that you must type
Italics
Indicates a new term
An Apply It section usually contains a segment of code that takes the lesson you just learned one step further Apply It sections offer inside information and pointers that you can use to enhance the functionality of your code
An Extra section provides additional information about the task you just accomplished Extra sections often contain interesting tips and useful tricks to make working with MySQL easier and more efficient
Please note that the majority of the tasks in this book are performed using the MySQL monitor Chapter 1 explains how to start the MySQL monitor The tasks in later chapters assume that the reader knows how to start the monitor or another MySQL client