To use MySQL to output the results of queries as HTML in a web page, requires a scripting language like PHP.
Queries are passed to MySQL as string arguments of PHP library functions and results are passed back as PHP array variables.
Connecting to MySQL
Before you can carry out operations on a database you must connect to the MySQL server.
This is done using the PHP function mysql_connect(). The function requires three arguments.
The hostname of the server where MySQL is running. If you are running scripts on your own machine this will be localhost.
If you are running your scripts on your web host's server it will probably be localhost also - check with your web host.
A username. If you are running scripts on your own machine this will be root by default.
If you are running your scripts on your web host's server then check with your web host.
A password. If you are running scripts on your own machine this will be the password you chose when you set up MySQL.
If you are running your scripts on your web host's server then check with your web host.
The mysql_connect() function must be present on all scripts that access MySQL and appear before any database operations.
The function either returns a connection handle or an error that will be output if mysql_error() is used.
Example of a Database Connection
<?php
$connection = mysql_connect("localhost", "username", "password") or exit(mysql_error());
?>
Custom Error Messages
MySQL error messages are not very user friendly therefore you can suppress them by using the @ character before functions and substituting your own error messages.
Example of a Custom Error Message
<?php
if (!($connection = @mysql_connect("localhost", "username", "password")))
{
echo('The MySQL server is not available');
exit;
}
?>
Selecting a Database
Once a connection has been made you can now select a database to work with using the mysql_select_db() function.
The function takes two arguments.
The name of the required database.
The connection handle returned by mysql_connect().
The function call can be made without the second argument and the call will assume the last connection opened.
But if the call fails then an attempt will be made to open another connection with no arguments and this will generate another error - so isn't recommended.
Example of a Selecting a Database
<?php
mysql_select_db("test", $connection) or exit(mysql_error());
?>