Main MySQL Page

Connecting to the Server

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.

Connecting to the MySQL Server

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().

Selecting the Database

Once the connection to the MySQL server has been established, you need to select the database you wish to query. This can be done with the following bulletproofed code.
   $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.

Using a Function

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

Using an Include File

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();

©2006 DFStermole
Created 15 Apr 06
Last Modified 2 May 08