A Wolf in the Library

Connecting to a MySQL database using PHP

The function used to connect to a MySQL database is mysql_connect. This should be called at the beginning of the page before any HTML tags.

mysql_connect follows the following format:

mysql_connect(host server name, user name, password)

Host server name is the name of your server. If your server is your local machine then you can just call it localhost otherwise you will need to contact your ISP to find out the server location and name. It should be something like http://www.myprovider.com/servername.

User name is the log in name used to get into your database (See: setting up a database in MySQL using phpMyadmin). If you haven't set up a user name then by default it will be root. For security reasons it is not a good idea to use the root user name. (See: setting up users in phpMyadmin).

Password is the password associated with the user name. Again by default there is no password and you could leave this option empty though it is highly recommended you create a password (See: setting up users in phpMyadmin).

In this example we will will be working on our localhost ( the server on my PC). Our user name will be chimpee and our password will be bananas.

Lets write a short script to connect to our database:
<?php

// creating variables to hold our log in information

$serverLocation = "localhost";
$userName = "chimpee";
$password = "bananas";

// making the connection

$connectDB = mysql_connect($serverLocation, $userName, $password)
or die ("This message will appear if the connection fails.");

?>

//HTML would begin here

That's it. Your page session should now connect to your localhost and you can begin to access all the databases chimpee has rights to access.