Knowledgebase: Using mySQL
How do I connect to mySQL through PHP?
Posted by Roy Petersen on Feb-15-2007 12:16 PM
Use the following outline to connect and begin querying the mySQL server from a PHP script. Remember that you cannot connect to your databases remotely due to security concerns, you can only connect from localhost.

1. Declarations
You must require the mySQL package for your script to function properly. Do this by including the following line in your code: use Mysql;

2. Connect To The Database
Somewhere near the beginning of your script, you need to make your initial connection to the database server. Using the following form, substitute your database, username, and password for the examples to connect successfully. The database must be a valid one that you have created through the PhpMyAdmin interface in the Control Panel. The username must be the one assigned to you and must have adequate permissions to the specified database.

Mysql->connect('localhost','DATABASENAME','USERNAME','USERPASSWORD');

3. Executing A Query
You are now ready to begin querying the database server. Most problems that you may incur will generally occur due to invalid permission settings for the specified user. Remember that you can use our convenient web based PhpMyAdmin interface to view or edit these settings.


Use the following outline to connect and begin querying the mySQL server from within your PHP scripts. Remember that you cannot connect to your databases remotely due to security reasons. You can only connect to them form localhost .

1. Connect To The mySQL Server
Use the following statement to connect to the database server. Substitute the username, and password for ones assigned to you.
MYSQL_CONNECT('localhost','USERNAME','PASSWORD');

2. Select Your Database
Use the following statement to select the database you wish to connect to. Make sure you substitute the example with your database name.
@mysql_select_db("DATABASENAME");

3. Executing A Query
You are now ready to execute your queries. Remember that the databases and users used must be created in the PhpMyAdmin interface in your Control Panel. Most problems that arise with your scripts will be due to incorrect permission settings.