» 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). EXAMPLE:

if your domain name is "bigtestserver.com"
if your account userid is "bigtest")
if you created a database named "games2"
if you created a database user named "baker"
if you assigned user dude the password "sam"
if you added baker to the games2 database
then you would enter the following logon/connection info:
database server type = mysql
server name = localhost
database name = bigtest_games2
database user name = bigtest_baker
database user password = sam

Was this answer helpful?

Add to favorites Add to Favourites
Print Print this Article