Knowledgebase: PHP
PHP/MySQL Tutorial - PHP MySQL Connection
Posted by Durand Somerville on 12 November 2011 01:01 AM

How to manually setup a mysql connection

Normally the password and the database name values are at the beginning of the script code.


You should replace "your_username", "your_password" and "your_database" with the MySQL username, password and database that will be used by your script.
(they should be already created with your control panel, by clicking on databases/ mysql wizard - filling in the prompts

Next connect your PHP script to the database. This can be done with the mysql_connect PHP function:


This line tells PHP to connect to the MySQL database server at 'localhost' (localhost is the MySQL server which usually runs on the same physical server as your script).

note - to view the mysql server name,  login to your control panel, select databases / mysql / to view sql server . replace localhost with the actuall mysql server name
(do not use the IP address, as the IP address can change)

use the following code to connect to your code

@mysql_select_db($database) or die( "Unable to select database");

This tells PHP to select the database stored in the variable $database ("your_database"). If the script cannot connect it will stop executing and will display the error:

Unable to select database

The 'or die' part is helps with debugging functionality. 

then close your connection using


This is a very important as it closes the connection to the database server.
Your script will still run if you do not include this function - creating many open MySQL connections which can cause problems for the server.

You can start querying the database now.



(0 vote(s))
Not helpful

Comments (0)
Post a new comment
Full Name:
CAPTCHA Verification 
Please enter the text you see in the image into the textbox below (we use this to prevent automated submissions).