Table of Contents
About the Author
Introduction
Chapter 1: Introducing PHP
Key PHP Features
Practicality
Power
Possibility
Price
The Current State of PHP
The PHP Ecosystem
Drupal
WordPress
Magento
MediaWiki
SugarCRM
Zend Framework
Summary
Chapter 2: Configuring Your Environment
Choosing a Hosting Environment
Virtual Servers
Platform as a Service (PaaS)
Installation Prerequisites
Windows
IIS
Apache
Nginx
macOS
Linux
From Source
Configure PHP
The Apache httpd.conf and .htaccess Files
Within the Executing Script
PHP’s Configuration Directives
Language Options
engine = On | Off
short_open_tag = On | Off
Precision = integer
output_buffering = On | Off | integer
output_handler = string
zlib.output_compression = On | Off | integer
zlib.output_handler = string
implicit_flush = On | Off
serialize_precision = integer
open_basedir = string
disable_functions = string
disable_classes = string
ignore_user_abort = Off | On
Miscellaneous
expose_php = On | Off
Resource Limits
max_execution_time = integer
max_input_time = integer
memory_limit = integerM
Data Handling
arg_separator.output = string
arg_separator.input = string
variables_order = string
register_argc_argv = On | Off
post_max_size = integerM
auto_prepend_file = string
auto_append_file = string
default_mimetype = string
default_charset = string
Paths and Directories
include_path = string
doc_root = string
user_dir = string
extension_dir = string
Fopen Wrappers
allow_url_fopen = On | Off
from = string
user_agent = string
default_socket_timeout = integer
auto_detect_line_endings = On | Off
Dynamic Extensions
extension = string
Choosing an Editor
PHPStorm
Atom
Sublime Text
Visual Studio Code
PDT (PHP Development Tools)
Zend Studio
Summary
Chapter 3: PHP Basics
Embedding PHP Code in Your Web Pages
Default Syntax
ShortTags
Embedding Multiple Code Blocks
Commenting Your Code
Single-Line C++ Syntax
Multiple-Line Comments
Outputting Data to the Client
Complex Output Using the printf() Statement
The sprintf() Statement
PHP’s Data Types
Scalar Data Types
Boolean
Integer
Float
String
Compound Data Types
Array
Object
Converting Between Data Types Using Type Casting
Adapting Data Types with Type Juggling
Type Identifier Functions
Manipulating Dynamic Data Using Variables
Variable Declaration
Assigning Values to Variables
Assigning Variables by Reference
PHP’s Superglobal Variables
Learning More About the Server and Client
Retrieving Variables Passed Using GET
Retrieving Variables Passed Using POST
Learning More About the Operating System Environment
Managing Constant Data with Constants
Defining a Constant
Taking Action with Expressions
Defining Inputs with Operands
Defining Actions with Operators
Operator Precedence
Understanding Operator Associativity
Introducing Arithmetic Operators
Assignment Operators
String Operators
Increment and Decrement Operators
Logical Operators
Equality Operators
Comparison Operators
Bitwise Operators
String Interpolation
Double Quotes
Escape Sequences
Single Quotes
Curly Braces
Heredoc
Nowdoc
Taking Control with Control Structures
Making Decisions with Conditional Statements
The if Statement
The else Statement
The elseif Statement
The switch Statement
Iterating Repeatedly with Looping Statements
The while Statement
The do...while Statement
The for Statement
The foreach Statement
The break Statement
The continue Statement
File-Inclusion Statements
The include() Statement
Ensuring a File Is Included Only Once
Requiring a File
Ensuring a File Is Required Only Once
Summary
Chapter 4: Functions
Invoking a Function
Creating a Function
Returning Multiple Values
Passing Arguments by Value
Default Argument Values
Using Type Declarations
Recursive Functions
Anonymous Functions
Function Libraries
Summary
Chapter 5: Arrays
What Is an Array?
Creating an Array
Creating Arrays with array()
Extracting Arrays with list()
Populating Arrays with a Predefined Value Range
Testing for an Array
Outputting an Array
Printing Arrays for Testing Purposes
Adding and Removing Array Elements
Adding a Value to the Front of an Array
Adding a Value to the End of an Array
Removing a Value from the Front of an Array
Removing a Value from the End of an Array
Locating Array Elements
Searching an Array
Searching Associative Array Keys
Searching Associative Array Values
Retrieving Array Keys
Retrieving Array Values
Extracting Columns
Traversing Arrays
Retrieving the Current Array Key
Retrieving the Current Array Value
Moving the Array Pointer
Moving the Pointer to the Next Array Position
Moving the Pointer to the Previous Array Position
Moving the Pointer to the First Array Position
Moving the Pointer to the Last Array Position
Passing Array Values to a Function
Determining Array Size and Uniqueness
Determining the Size of an Array
Counting Array Value Frequency
Determining Unique Array Values
Sorting Arrays
Reversing Array Element Order
Flipping Array Keys and Values
Sorting an Array
Sorting an Array While Maintaining Key/Value Pairs
Sorting an Array in Reverse Order
Sorting an Array in Reverse Order While Maintaining Key/Value Pairs
Sorting an Array Naturally
Case-Insensitive Natural Sorting
Sorting an Array by Key Values
Sorting Array Keys in Reverse Order
Sorting According to User-Defined Criteria
Merging, Slicing, Splicing, and Dissecting Arrays
Merging Arrays
Recursively Appending Arrays
Combining Two Arrays
Slicing an Array
Splicing an Array
Calculating an Array Intersection
Calculating Associative Array Intersections
Calculating Array Differences
Calculating Associative Array Differences
Other Useful Array Functions
Returning a Random Set of Keys
Shuffling Array Elements
Adding Array Values
Subdividing an Array
Summary
Chapter 6: Object-Oriented PHP
The Benefits of OOP
Encapsulation
Inheritance
Polymorphism
Key OOP Concepts
Classes
Objects
Properties
Declaring Properties
Invoking Properties
Managing Property Scopes
Public Properties
Private Properties
Protected Properties
Property Overloading
Setting Properties with the __set() Method
Getting Properties with the __get() Method
Creating Custom Getters and Setters
Constants
Methods
Declaring Methods
Invoking Methods
Method Scopes
Public Methods
Private Methods
Protected
Abstract
Final
Constructors and Destructors
Constructors
Inheritance
Invoking Parent Constructors
Destructors
Type Hinting
Static Class Members
The instanceof Keyword
Helper Functions
Determining Whether a Class Exists
Determining Object Context
Learning About Class Methods
Learning About Class Properties
Learning About Declared Classes
Learning About Object Properties
Determining an Object’s Parent Class
Determining Object Type
Determining Object Subclass Type
Determining Method Existence
Autoloading Objects
Traits
Summary
Chapter 7: Advanced OOP Features
Advanced OOP Features Not Supported by PHP
Object Cloning
Cloning Example
The __clone() Method
Inheritance
Class Inheritance
Inheritance and Constructors
Inheritance and Late Static Binding
Interfaces
Implementing a Single Interface
Implementing Multiple Interfaces
Determining Interface Existence
Abstract Classes
Introducing Namespaces
Summary
Chapter 8: Error and Exception Handling
All Your Bugs Belong to You
Configuring PHP’s Error Reporting Behavior
Setting the Desired Error Sensitivity Level
Displaying Errors Within the Browser
Logging Errors
Creating and Logging Custom Messages
Exception Handling
Why Exception Handling Is Handy
PHP’s Exception-Handling Capabilities
Extending the Base Exception Class
The Default Constructor
Introducing the Finally Block
Extending the Exception Class
Catching Multiple Exceptions
Standard PHP Library Exceptions
Error Handling in PHP 7
Summary
Chapter 9: Strings and Regular Expressions
Regular Expressions
Regular Expression Syntax (Perl)
Modifiers
Metacharacters
PHP’s Regular Expression Functions (Perl Compatible)
Searching for a Pattern
Matching All Occurrences of a Pattern
Searching an Array
Delimiting Special Regular Expression Characters
Replacing All Occurrences of a Pattern
Creating a Custom Replacement Function
Splitting a String into Various Elements Based on a Case-Insensitive Pattern
Other String-Specific Functions
Determining the Length of a String
Comparing Two Strings
Comparing Two Strings’ Case Sensitively
Comparing Two Strings’ Case Insensitively
Calculating the Similarity Between Two Strings
Calculating the Difference Between Two Strings
Manipulating String Case
Converting a String to All Lowercase
Converting a String to All Uppercase
Capitalizing the First Letter of a String
Capitalizing Each Word in a String
Converting Strings to and from HTML
Converting Newline Characters to HTML Break Tags
Converting Special Characters to Their HTML Equivalents
Using Special HTML Characters for Other Purposes
Converting Text into Its HTML Equivalent
Creating a Customized Conversion List
Converting HTML to Plain Text
Alternatives for Regular Expression Functions
Tokenizing a String Based on Predefined Characters
Exploding a String Based on a Predefined Delimiter
Converting an Array into a String
Performing Complex String Parsing
Finding the Last Occurrence of a String
Replacing All Instances of a String with Another String
Retrieving Part of a String
Returning Part of a String Based on Predefined Offsets
Determining the Frequency of a String’s Appearance
Replacing a Portion of a String with Another String
Padding and Stripping a String
Trimming Characters from the Beginning of a String
Trimming Characters from the End of a String
Trimming Characters from Both Sides of a String
Padding a String
Counting Characters and Words
Counting the Number of Characters in a String
Counting the Total Number of Words in a String
Summary
Chapter 10: Working with the File and Operating System
Learning About Files and Directories
Directory Separators
Parsing Directory Paths
Retrieving a Path’s Filename
Retrieving a Path’s Directory
Learning More About a Path
Identifying the Absolute Path
Calculating File, Directory, and Disk Sizes
Determining a File’s Size
Calculating a Disk’s Free Space
Calculating Total Disk Size
Retrieving a Directory Size
Determining Access and Modification Times
Determining a File’s Last Access Time
Determining a File’s Last Changed Time
Determining a File’s Last Modified Time
Working with Files
The Concept of a Resource
Recognizing Newline Characters
Recognizing the End-of-File Character
Opening and Closing a File
Opening a File
Closing a File
Reading from a File
Reading a File into an Array
Reading File Contents into a String Variable
Reading a CSV File into an Array
Reading a Specific Number of Characters
Stripping Tags from Input
Reading a File One Character at a Time
Ignoring Newline Characters
Outputting an Entire File
Reading a File According to a Predefined Format
Writing a String to a File
Tip Moving the File Pointer
Moving the File Pointer to a Specific Offset
Retrieving the Current Pointer Offset
Moving the File Pointer Back to the Beginning of the File
Reading Directory Contents
Opening a Directory Handle
Closing a Directory Handle
Parsing Directory Contents
Reading a Directory into an Array
Executing Shell Commands
Removing a Directory
Renaming a File
Touching a File
System-Level Program Execution
Sanitizing the Input
Delimiting Input
Escaping Potentially Dangerous Input
PHP’s Program Execution Functions
Executing a System-Level Command
Retrieving a System Command’s Results
Returning Binary Output
Executing a Shell Command with Backticks
An Alternative to Backticks
Summary
Chapter 11: Third-Party Libraries
Introducing PEAR
Installing PEAR
Updating PEAR
Using the PEAR Package Manager
Installing a PEAR Package
Automatically Installing All Dependencies
Viewing Installed PEAR Packages
Introducing Composer
Installing Composer
Installing Composer on Linux and macOS
Installing Composer on Windows
Using Composer
Extending PHP with C Libraries
Summary
Chapter 12: Date and Time
The Unix Timestamp
PHP’s Date and Time Library
Validating Dates
Formatting Dates and Times
Working with Time
Learning More About the Current Time
Converting a Timestamp to User-Friendly Values
Working with Timestamps
Determining the Current Timestamp
Creating a Timestamp Based on a Specific Date and Time
Date Fu
Displaying the Localized Date and Time
Setting the Default Locale
Localizing Dates and Times
Displaying the Web Page’s Most Recent Modification Date
Determining the Number of Days in the Current Month
Determining the Number of Days in Any Given Month
Calculating the Date X Days from the Present Date
Date and Time Classes
Introducing the DateTime Constructor
Formatting Dates
Setting the Date After Instantiation
Setting the Time After Instantiation
Modifying Dates and Times
Calculating the Difference Between Two Dates
Summary
Chapter 13: Forms
PHP and Web Forms
A Simple Example
Validating Form Data
File Deletion
Cross-Site Scripting
Sanitizing User Input
Escaping Shell Arguments
Escaping Shell Metacharacters
Converting Input into HTML Entities
Stripping Tags from User Input
Validating and Sanitizing Data with the Filter Extension
Sanitizing Data with the Filter Extension
Working with Multivalued Form Components
Summary
Chapter 14: Authenticating Your Users
HTTP Authentication Concepts
Using Apache’s .htaccess Feature
Authenticating Your Users with PHP
PHP’s Authentication Variables
Useful Functions
Sending HTTP Headers with header()
Determining If a Variable Is Set with isset()
PHP Authentication Methodologies
Hard-Coded Authentication
File-Based Authentication
Database-Based Authentication
User Login Administration
Password Hashing
One-Time URLs and Password Recovery
Using OAuth 2.0
Summary
Chapter 15: Handling File Uploads
Uploading Files via HTTP
Uploading Files with PHP
PHP’s File Upload/Resource Directives
file_uploads = On | Off
max_input_time = integer
max_file_uploads = integer
memory_limit = integer
post_max_size = integer
upload_max_filesize = integer
upload_tmp_dir = string
The $_FILES Array
PHP’s File-Upload Functions
Determining Whether a File Was Uploaded
Moving an Uploaded File
Upload Error Messages
A Simple Example
Summary
Chapter 16: Networking
DNS, Services, and Servers
DNS
Checking for the Existence of DNS Records
Retrieving DNS Resource Records
Retrieving MX Records
Services
Retrieving a Service’s Port Number
Retrieving a Port Number’s Service Name
Establishing Socket Connections
Mail
Configuration Directives
SMTP = string
sendmail_from = string
sendmail_path = string
smtp_port = integer
mail.force_extra_parameters = string
Sending E-mail Using a PHP Script
Sending a Plain-Text E-mail
Taking Advantage of PHPMailer
Installing PHPMailer
Sending an E-mail with PHPMailer
Common Networking Tasks
Pinging a Server
Creating a Port Scanner
Creating a Subnet Converter
Summary
Chapter 17: Session Handlers
What Is Session Handling?
The Session-Handling Process
Configuration Directives
Managing the Session Storage Media
Setting the Session Files Path
Automatically Enabling Sessions
Setting the Session Name
Choosing Cookies or URL Rewriting
Setting the Session Cookie Lifetime
Setting the Session Cookie’s Valid URL Path
Setting the Session Cookie’s Valid Domain
Setting Caching Directions
Setting Cache Expiration Time for Session-Enabled Pages
Setting the Session Lifetime
Working with Sessions
Starting a Session
Destroying a Session
Setting and Retrieving the Session ID
Creating and Deleting Session Variables
Encoding and Decoding Session Data
Encoding Session Data
Decoding Session Data
Regenerating Session IDs
Practical Session-Handling Examples
Automatically Logging In Returning Users
Generating a Recently Viewed Document Index
Creating Custom Session Handlers
Tying Custom Session Functions into PHP’s Logic
Using Custom MySQL-Based Session Handlers
Summary
Chapter 18: Web Services
Why Web Services?
Getting Started with APIs
API Security
Create an API
Summary
Chapter 19: Secure PHP Programming
Configuring PHP Securely
Security-Related Configuration Parameters
disable_functions = string
disable_classes = string
display_errors = On | Off
max_execution_time = integer
memory_limit = integerM
open_basedir = string
user_dir = string
Hiding Configuration Details
Hiding Apache
Apache’s ServerSignature Directive
Apache’s ServerTokens Directive
Hiding PHP
expose_php = 1 | 0
Remove All Instances of phpinfo() Calls
Change the Document Extension
Hiding Sensitive Data
Hiding the Document Root
Denying Access to Certain File Extensions
Data Encryption
PHP’s Encryption Functions
Hashing Data with the hash() Hash Function
Encrypting Data Using OpenSSL
Summary
Chapter 20: Integrating jQuery and PHP
Introducing Ajax
Introducing jQuery
Installing jQuery
A Simple Example
Responding to Events
jQuery and the DOM
Modifying Page Elements
Creating a Username Existence Validator
Determining If a Username Exists
Integrating the Ajax Functionality
Summary
Chapter 21: MVC and Frameworks
Introducing MVC
PHP’s Framework Solutions
The CakePHP Framework
The Symfony Framework
The Zend Framework
The Phalcon Framework
The Laravel Framework
The PHP Framework Interoperability Group (PHP-FIG)
PSR-1 and PSR-2 Coding Standards
PSR-4 Autoloading
Summary
Chapter 22: Introducing MySQL
What Makes MySQL So Popular?
Flexibility
Power
Enterprise-Level SQL Features
Full-Text Indexing and Searching
Query Caching
Replication
Configuration and Security
Flexible Licensing Options
MySQL Open Source License
Standard, Enterprise, and Cloud License
Which License Should You Use?
Prominent MySQL Users
Craigslist
Twitter
GitHub
Other Prominent Users
MariaDB: An Alternative to MySQL
Summary
Chapter 23: Installing and Configuring MySQL
Downloading MySQL
Installing MySQL
Installing MySQL on Linux
RPM, Binary, or Source?
The RPM Installation Process
The Binary Installation Process
The Source Installation Process
Installing and Configuring MySQL on Windows
Installing MySQL on Windows
Starting and Stopping MySQL
Controlling the Daemon Manually
Starting MySQL on Linux
Starting MySQL on Windows
Stopping MySQL on Linux and Windows
Configuring and Optimizing MySQL
The mysqld_safe Wrapper
MySQL’s Configuration and Optimization Parameters
Viewing MySQL’s Configuration Parameters
Managing Connection Loads
Setting the Data Directory Location
Setting the Default Storage Engine
Automatically Executing SQL Commands
Logging Potentially Nonoptimal Queries
Logging Slow Queries
Setting the Maximum Allowable Simultaneous Connections
Setting MySQL’s Communication Port
Disabling DNS Resolution
Limiting Connections to the Local Server
Setting the MySQL Daemon User
The my.cnf File
Configuring PHP to Work with MySQL
Reconfiguring PHP on Linux
Reconfiguring PHP on Windows
Summary
Chapter 24: The Many MySQL Clients
Introducing the Command-Line Clients
The mysql Client
Interacting with MySQL
Using mysql in Batch Mode
Useful mysql Tips
Displaying Results Vertically
Logging Queries
Getting Server Statistics
Preventing Accidents
Modifying the mysql Prompt
Viewing Configuration Variables and System Status
Useful mysql Options
The mysqladmin Client
mysqladmin Commands
Other Useful Clients
mysqlshow
Useful GUI Client Programs
phpMyAdmin
Summary
Chapter 25: MySQL Storage Engines and Data Types
Storage Engines
InnoDB
MyISAM
MyISAM Static
MyISAM Dynamic
MyISAM Compressed
MEMORY
MERGE
FEDERATED
ARCHIVE
CSV
EXAMPLE
BLACKHOLE
Storage Engine FAQ
Which Storage Engines Are Available on My Server?
How Do I Take Advantage of the Storage Engines on Windows?
Is It Wrong to Use Multiple Storage Engines Within the Same Database?
How Can I Specify a Storage Engine at Creation Time or Change It Later?
I Need Speed! What’s the Fastest Storage Engine?
Data Types and Attributes
Data Types
Date and Time Data Types
DATE
DATETIME
TIME
TIMESTAMP [DEFAULT] [ON UPDATE]
YEAR[(2|4)]
Numeric Data Types
BOOL, BOOLEAN
BIGINT [(M)]
INT [(M)] [UNSIGNED] [ZEROFILL]
MEDIUMINT [(M)] [UNSIGNED] [ZEROFILL]
SMALLINT [(M)] [UNSIGNED] [ZEROFILL]
TINYINT [(M)] [UNSIGNED] [ZEROFILL]
DECIMAL([M[,D]]) [UNSIGNED] [ZEROFILL]
DOUBLE([M,D]) [UNSIGNED] [ZEROFILL]
FLOAT([M,D]) [UNSIGNED] [ZEROFILL]
FLOAT (precision) [UNSIGNED] [ZEROFILL]
String Data Types
[NATIONAL] CHAR(Length) [BINARY | ASCII | UNICODE]
[NATIONAL] VARCHAR(Length) [BINARY]
LONGBLOB
LONGTEXT
MEDIUMBLOB
MEDIUMTEXT
BLOB
TEXT
TINYBLOB
TINYTEXT
ENUM(“member1”,“member2”,…“member65,535”)
SET(“member1”, “member2”,…“member64”)
Spatial Data Types
JSON Data Types
Data Type Attributes
AUTO_INCREMENT
BINARY
DEFAULT
INDEX
NATIONAL
NOT NULL
NULL
PRIMARY KEY
UNIQUE
ZEROFILL
Working with Databases and Tables
Working with Databases
Viewing Databases
Creating a Database
Using a Database
Deleting a Database
Working with Tables
Creating a Table
Conditionally Creating a Table
Copying a Table
Creating a Temporary Table
Viewing a Database’s Available Tables
Viewing a Table Structure
Deleting a Table
Altering a Table Structure
The INFORMATION_SCHEMA
Summary
Chapter 26: Securing MySQL
What You Should Do First
Securing the mysqld Daemon
The MySQL Access Privilege System
How the Privilege System Works
The Two Stages of Access Control
Tracing a Real-World Connection Request
Where Is Access Information Stored?
The user Table
Host
User
Password
The Privilege Columns
The db Table
The host Table
The tables_priv Table
The columns_priv Table
The procs_priv Table
User and Privilege Management
Creating Users
Deleting Users
Renaming Users
The Grant and Revoke Commands
Granting Privileges
Creating a New User and Assigning Initial Privileges
Adding Privileges to an Existing User
Granting Table-Level Privileges
Granting Multiple Table-Level Privileges
Granting Column-Level Privileges
Revoking Privileges
Revoking Previously Assigned Permissions
Revoking Table-Level Permissions
Revoking Column-Level Permissions
Deleting a User
GRANT and REVOKE Tips
Reviewing Privileges
SHOW GRANTS FOR
Limiting User Resources
Secure MySQL Connections
Grant Options
REQUIRE SSL
REQUIRE X509
REQUIRE ISSUER
REQUIRE SUBJECT
REQUIRE CIPHER
SSL Options
--ssl
--ssl-ca
--ssl-capath
--ssl-cert
--ssl-cipher
--ssl-key
Starting the SSL-Enabled MySQL Server
Connecting Using an SSL-Enabled Client
Storing SSL Options in the my.cnf File
Summary
Chapter 27: Using PHP with MySQL
Installation Prerequisites
Enabling the mysqli Extension on Linux/Unix
Enabling the mysqli Extension on Windows
Using the MySQL Native Driver
Managing User Privileges
Working with Sample Data
Using the mysqli Extension
Setting Up and Tearing Down the Connection
Handling Connection Errors
Retrieving Error Information
Retrieving Error Codes
Retrieving Error Messages
Storing Connection Information in a Separate File
Securing Your Connection Information
Interacting with the Database
Sending a Query to the Database
Retrieving Data
Inserting, Updating, and Deleting Data
Recuperating Query Memory
Parsing Query Results
Fetching Results into an Object
Retrieving Results Using Indexed and Associative Arrays
Determining the Rows Selected and Rows Affected
Determining the Number of Rows Returned
Determining the Number of Affected Rows
Working with Prepared Statements
Preparing the Statement for Execution
Executing a Prepared Statement
Recuperating Prepared Statement Resources
Binding Parameters
Binding Variables
Retrieving Rows from Prepared Statements
Using Other Prepared Statement Methods
Executing Database Transactions
Enabling Autocommit Mode
Committing a Transaction
Rolling Back a Transaction
Summary
Chapter 28: Introducing PDO
Another Database Abstraction Layer?
PDO’s Database Options
Using PDO
Installing PDO
Connecting to a Database Server and Selecting a Database
Embedding the Parameters into the Constructor
Placing the Parameters in a File
Referring to the php.ini File
Using PDO’s Connection-Related Options
Handling Connection Errors
Handling Errors
Retrieving SQL Error Codes
Retrieving SQL Error Messages
Getting and Setting Attributes
Retrieving Attributes
Setting Attributes
Executing Queries
Adding, Modifying, and Deleting Table Data
Selecting Table Data
Introducing Prepared Statements
Using Prepared Statements
Executing a Prepared Query
Binding Parameters
Retrieving Data
Returning the Number of Retrieved Columns
Retrieving the Next Row in the Result Set
Simultaneously Returning All Result Set Rows
Fetching a Single Column
Setting Bound Columns
Working with Transactions
Beginning a Transaction
Committing a Transaction
Rolling Back a Transaction
Summary
Chapter 29: Stored Routines
Should You Use Stored Routines?
Stored Routine Advantages
Stored Routine Disadvantages
How MySQL Implements Stored Routines
Creating a Stored Routine
Setting Security Privileges
Setting Input and Return Parameters
Characteristics
LANGUAGE SQL
[NOT] DETERMINISTIC
CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA
SQL SECURITY {DEFINER | INVOKER}
COMMENT ‘string’
Declaring and Setting Variables
Declaring Variables
Setting Variables
Executing a Stored Routine
Creating and Using Multistatement Stored Routines
The BEGIN and END Block
Conditionals
IF-ELSEIF-ELSE
CASE
Iteration
ITERATE
LEAVE
LOOP
REPEAT
WHILE
Calling a Routine from Within Another Routine
Modifying a Stored Routine
Deleting a Stored Routine
Viewing a Routine’s Status
Viewing a Routine’s Creation Syntax
Handling Conditions
Integrating Routines into Web Applications
Creating the Employee Bonus Interface
Retrieving Multiple Rows
Summary
Chapter 30: MySQL Triggers
Introducing Triggers
Why Use Triggers?
Taking Action Before an Event
Taking Action After an Event
Before Triggers vs. After Triggers
MySQL’s Trigger Support
Creating a Trigger
Viewing Existing Triggers
The SHOW TRIGGERS Command
The INFORMATION_SCHEMA
Modifying a Trigger
Deleting a Trigger
Integrating Triggers into Web Applications
Summary
Chapter 31: MySQL Views
Introducing Views
MySQL’s View Support
Creating and Executing Views
Customizing View Results
Passing in Parameters
Modifying the Returned Column Names
Using the ALGORITHM Attribute
MERGE
TEMPTABLE
UNDEFINED
Using Security Options
Using the WITH CHECK OPTION Clause
Viewing View Information
Using the DESCRIBE Command
Using the SHOW CREATE VIEW Command
Using the INFORMATION_SCHEMA Database
Modifying a View
Deleting a View
Updating Views
Incorporating Views into Web Applications
Summary
Chapter 32: Practical Database Queries
Sample Data
Creating Tabular Output
Installing HTML_Table
Creating a Simple Table
Creating More Readable Row Output
Creating a Table from Database Data
Sorting Output
Creating Paged Output
Listing Page Numbers
Querying Multiple Tables with Subqueries
Performing Comparisons with Subqueries
Determining Existence with Subqueries
Performing Database Maintenance with Subqueries
Using Subqueries with PHP
Iterating Result Sets with Cursors
Cursor Basics
Creating a Cursor
Opening a Cursor
Using a Cursor
Closing a Cursor
Using Cursors with PHP
Summary
Chapter 33: Indexes and Searching
Database Indexing
Primary Key Indexes
Unique Indexes
Normal Indexes
Single-Column Normal Indexes
Multiple-Column Normal Indexes
Full-Text Indexes
Stopwords
Boolean Full-Text Searches
Indexing Best Practices
Forms-Based Searches
Performing a Simple Search
Extending Search Capabilities
Performing a Full-Text Search
Summary
Chapter 34: Transactions
What’s a Transaction?
MySQL’s Transactional Capabilities
System Requirements
Table Creation
A Sample Project
Creating Tables and Adding Sample Data
The participants Table
The trunks Table
Adding Some Sample Data
Executing an Example Transaction
Usage Tips
Building Transactional Applications with PHP
The Swap Meet Revisited
Summary
Chapter 35: Importing and Exporting Data
Sample Table
Using Data Delimitation
Importing Data
Importing Data with LOAD DATA INFILE
A Simple Data Import Example
Choosing the Target Database
Security and LOAD DATA INFILE
Importing Data with mysqlimport
Useful Options
Writing a mysqlimport Script
Loading Table Data with PHP
Exporting Data
SELECT INTO OUTFILE
Usage Tips
A Simple Data Export Example
Exporting MySQL Data to Microsoft Excel
Summary
Index