Connecting PHP and MySQL
Create a simple page
This example will show how to use PHP to connect to a MYSQL database. This example will assume that you have already
created a database and table, using your control center in the database section.
First thing is open some text editor (notepad, Dreamweaver, UltraEdit, vi, ..etc). First we need to define our
connection details: host, username, password, database name and table. The information is set in your control center.
Below is the PHP to do so:
//function to connect to a database
function dbConnect()
{
//define the database connection information
$dbHost = "localhost";
$dbUser = "username";
$dbPass = "password";
$dbName = "nameofdatabase";
//connect to the mysql server
$link = @mysql_connect($dbHost, $dbUser, $dbPass);
//return success or failure of connection
if(!$link)
{
//report error
echo "Could not connect to server";
exit;
}
//select the database
if(!@mysql_select_db($dbName))
{
//report error
echo "Could not select database";
exit;
}
}
Well that seemed like quite a mouthful didn't it? Now let's go through the code and explain what each section means. The first section you are just creating variables which are needed to connect to the database.
//define the database connection information
$dbHost = "localhost";
$dbUser = "username";
$dbPass = "password";
$dbName = "nameofdatabase";
The variable dbHost should be set to localhost if it is residing on the same server as your other files. This is normally set to localhost. 'dbUser, dbPass, and dbName' are: the user for the database (which was created in PHPMYADMIN or some other method), and dbName is the name of the database.
//connect to the mysql server
= @mysql_connect(, , );
The variable 'link' is created which calls the mysql function 'connect'. The function sends the Hostname, Username, and Password in order to connect.
//return success or failure of connection
if(!$link) {
//report error
echo "Could not connect to database";
exit;
}
This IF statement sees if the connection was successful. The '!link' means 'NOT link, meaning unsuccessful'. If this is the case it prints out the error message 'Could not connect to server.'
//select the database
if(!@mysql_select_db($dbName))
{
//report error
echo "Could not select database";
exit;
}
This final IF statement attempts to select the database, ONLY if the connection to the server was successful (link). If it cannot select the database, it will print out the relative error message, 'Could not select database.'
So from the script you can see that connecting to the database is quite simple. It involves three steps: declaring the variables, connecting to the server, and finally selecting the database. I hope this tutorial helps you understand the link between PHP and MYSQL a little better.
Back to Online Manual
|