Check MySQL database connection using PHP test script

As a tech I’ve been in situations when a database is not working or the connection to it is interrupted.

This tutorial will show you how can be done MySQL database connection check using PHP script.

The above MySQL connection test script is using mysql_connect(); function which is designed to open a connection to a MySQL Server.

The full parameters of the function are:

It looks rather complicated for a beginner look, but the function is just explained with the variables parameters that can carry.

Now to check whether your MySQL database is working, do the following:

Copy and past the first code into ‘database_test_file.php’ for example.Replace ”db_host”, ”db_username”, ”db_password” with the real credentials.
You should have this information from your hosting provider, but if you are in doubt I will explain briefly:

For db_host your should put either: localhost , mysql.domain.tld, db_hosting_server.tld or IP address.

Localhost ‘“ this will point the script to the same server where your website files are hosted. In most cases that will be the default address for the database.

mysql.domain.tld ‘“ if the database server is separated from your hosting your hosting provider probably will provide you with such address which is setup using ‘A’ record or ‘CNAME’ to point to it.

db_hosting_server.tld ‘“ yout hosting provider may give you directly the database server name

IP address ‘“ in format with three digit numbers divided by dots ‘225.225.225.225’ when the database server has no name but directly points to an IP address.

When you are ready with the right setup of the script upload the file on your hosting and execute the script to test the database with something like:

http://domain.tld/database_test_file.php

If you receive:

Connected to the database successfully

– it is obvious that the PHP script is connecting to the database .

The opposite will be:

Could not connect (MySQL error)

Then the database is either not working, there is no connection to it, you have put wrong credentials or there is no database activated on your hosting.
If that is the case I suggest to search trough Internet for the MySQL error that the script returns and /or to contact your hosting provider for more information.

If you are looking for more PHP tutorials you may check this article: PHP tutorials

Tags

Filed Under: PHP

Anthony Gee About the Author: Anthony G. is an IT specialist with more than 9 years of solid working experience in the Web Hosting industry. Currently works as server support administrator, involved in consultative discussions about Web Hosting and server administration. One of the first writers in the Onlinehowto.net website, now writing for Free Tutorials community - he is publishing tutorials and articles for the wide public, as well as specific technical solutions.

Comments (1)

  1. Ron says:

    Simple and accurate script. Thank you!

Leave a Reply