Chapter 19. PHP API
One of the most popular programming language and database engine
combinations for the Web is PHP with MySQL. This combination works well for
many reasons, but primarily because of the speed, stability, and simplicity
of both applications. The first part of this chapter provides a basic
tutorial on how to connect to and query MySQL with PHP. Following the
tutorial is a reference of PHP MySQL functions in alphabetical order. For
the examples in this chapter, I use the database of a fictitious computer
support business. This database contains one table with client work requests
(workreq) and another with client contact information
(clients).
Using PHP with MySQL
This section presents the basic tasks you need to query a MySQL
database from PHP. Prior to PHP 5, MySQL was enabled by default. As of PHP
5, it’s not enabled and the MySQL library is not packaged with PHP. To
enable MySQL with PHP, you need to configure PHP with the
--with-mysql[=/
option.path_to_mysql]
Connecting to MySQL
For a PHP script to interface with MySQL, the script must first make
a connection to MySQL, thus establishing a MySQL session. To connect to
the fictitious database workrequests, a PHP script
might begin like this:
<?php $host = 'localhost'; $user = 'russell'; $pw = 'dyer'; $db = 'workrequests'; mysql_connect($host, $user, $pw) or die(mysql_error); mysql_select_db($db); ?>
This excerpt of PHP code starts by establishing the variables with information necessary for connecting to MySQL and the ...