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[=/path_to_mysql] option.

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:

$host = 'localhost';
$user = 'russell';
$pw = 'dyer';
$db = 'workrequests';
mysql_connect($host, $user, $pw)
   or die(mysql_error);

This excerpt of PHP code starts by establishing the variables with information necessary for connecting to MySQL and the database. After that, PHP connects to MySQL by giving the host and user variables. If it’s unsuccessful, the script dies with an error message. If the connection is successful, the workrequests database is selected for use. Each PHP script example in this chapter begins with an excerpt of code like this one.

Querying MySQL

In the fictitious database is a table called workreq that contains information on client work requests. To retrieve a list of work requests and some basic information on clients, a PHP script begins by connecting to MySQL, as shown in the previous script excerpt. That is followed by the start of a web page and then the invocation of an SQL ...

Get MySQL in a Nutshell, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.