Quick Links
All SQL operations can be performed using mysql when it is run from the Command Line. A much more user-friendly method is to use phpMyAdmin. Once you have your data in table(s) in your own database and you have checked it using mysql and/or phpMyAdmin, it is time to program a PHP front end.
This introduction to MySQL does not deal with security issues. (You can check other web sites for that information.) The following code attempts to connect to the MySQL server using the default user.
$id_link = mysql_connect('localhost', 'root', '');
if (! $id_link)
die( "The connection to the local MySQL server has failed.");
If the connection is successful, mysql_connect() returns a non-zero resource id, stored here in $id_link. If the value returned is zero, there is no sense in continuing with the PHP program, so it is terminated with end().
$dbexists = mysql_select_db( "pirates" );
if(! $dbexists)
die("pirates database not found!");
mysql_select_db returns a Boolean value, true or false. Here it is assigned to the $dbexists variable. If the value is false, the script is terminated, stating that the database was not found.
Both of these requests can be placed in a function.
function myconnect()
{
$id_link = mysql_connect('localhost', 'root', '');
if (! $id_link)
die( "The connection to the local MySQL server has failed.");
$dbexists = mysql_select_db( "pirates" );
if(! $dbexists)
die("pirates database not found!");
} // end myconnect
If you are going to have numerous PHP scripts each of which uses the database, you can produce cleaner code by placing the function in an include file. Here is what the file could look like.
<?php
// common.php for accessing pirates database
function myconnect()
{
$id_link = mysql_connect('localhost', 'root', '');
if (! $id_link)
die( "The connection to the local MySQL server has failed.");
$dbexists = mysql_select_db( "pirates" );
if(! $dbexists)
die("pirates database not found!");
} // end myconnect
?>
To make this function available and to execute it, all you need to do is place the following two lines of code in your PHP script.
include('common.php');
myconnect();