PHP has an extensive library of functions to interact with MySQL. Open HTML-Kit, or whatever HTML editor you use, click on the PHP button on the Actions Bar and look at the MySQL drop-down list. See also http://www.php.net/manual/en/ref.mysql.php. After writing several of your own programs, you will likely have used most of these functions.
The patriarch of all PHP functions that deal with MySQL is mysql_query(). Once you are linked to MySQL, you can perform any and all of the SQL commands we learned by inserting them in this function. Mysql_query("update table People set NAME_LAST='Smith' where FLITE_ID='bsmith'") will update the table. Mysql_query('alter table people add COMPONENT char(15) NOT NULL') will add that field to the table.
mysql_query('select * from people') will select all the data, but without further instructions, PHP will not display it on the screen.
PHP has gathered some of the most common tasks as well as some of the more complicated ones into functions to make your life easier. I group the functions into the following categories:
- Connecting to MySQL
- Accessing Tables
- Sending Queries and Retrieving Data
Here are the PHP functions for connecting to MySQL. Those highlighted in light green are considered advanced and will not be taught here, but the links are still provided for your future reference.
Mysql_connect() establishes a connection to a MySQL server. It takes the following parameters: [server], [username] and [password]. It returns a MySQL link identifier on success, or FALSE on failure. Here's an example:
$link is the MySQL link identifier. If the connection was successful, this identifier will be used throughout the script in retrieving data. If the connection was unsuccessful, $link=FALSE, and the die function is called. The die function (which is an alias for the exit function) terminates the script and displays its string parameter (in this case, it displays "Could not connect").
Using mysql_close() isn't usually necessary, since any link opened with mysql_connect() closes automatically when the script ends. But if you ever wanted to close the current link, the syntax is: