This section presents the basic tasks you need to query a MySQL database from PHP.
For a PHP script to interface to MySQL, first you must make a connection to it, thus establishing a MySQL session. To connect to the workrequests database, a PHP script might begin like so:
<?php $host = 'localhost'; $user = 'russell'; $pw = 'dyer'; $db = 'workrequests'; mysql_connect($host, $user, $pw) or die(mysql_error); mysql_select_db($db); ?>
This section 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, though, the workrequests database is selected for use. Each PHP script example in this chapter begins with a section of code like this one.
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 statement to retrieve and display the data. You can achieve this with code such as the following:
... // Connect to MySQL <html> <body> <h2>Work Requests</h2> <?php $sql_stmnt = "SELECT wrid, client_name, wr_date, description FROM workreq, ...