How do I Connect to MySQL with PHP?

Here's how to connect and begin querying the MySQL server from within your PHP scripts:
1. Connect to the MySQL server: Use this statement to connect to the database server. Replace the username and password with the ones who were created in the MyAdmin interface and have given adequate permissions to this database:
MYSQL_CONNECT('localhost','USERNAME','PASSWORD');

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

3. Executing A Query: Now you can execute your queries. Remember that the databases and users used must be created in the MyAdmin of your CPanel. Most problems that arise with scripts are because of incorrect permission settings.

Troubleshooting "Cannot connect to the database" errors - Here are a few common mistakes:
a. Make sure that you didn't forget to ADD the database user to the database after you created your database and database user. (at the bottom of the "Databases" section in Control Panel - MySQL Manager, there are two drop down menus, "User:" and "DB:" then an "Add User to DB" button).

b. Check that you entered localhost as the database host/server name and if applicable, that you specified mysql for the database server type.

c. Check that you specified the correct database and database user names. Remember that these are case sensitive and that your account userid (usually the first 7 characters of your domain name) is added with an underscore as a prefix to both your database and database user names (userid_dbname rather than just dbname and userid_dbuser instead of just dbuser).

d. Make sure that you use the password that you assigned to your database user in MySQL Manager (NOT your account password).

  • 14 Users Found This Useful
Was this answer helpful?

Related Articles

What is PHP?

PHP is a server-side HTML embedded scripting language used to create scripts and/or Web pages. In...

What extensions do I use for PHP?

You can use .php, .php3 .phtml, .php4

Why do I get a PHP 500 Error?

Normallly, the permissions on php files should be 644 and the permissions on folders containing...

How do I create a new database?

To create a new database, log into your control panel and click the "Manage Mysql" link. You will...