Test Database connectivity using PHP script

1Many times, A system administrator needs to test a connection between APP server and DB server. It can be required when some developer reporting issue while they connect to the Database server from their application. 

It is a very helpful PHP script that gives us very useful output and can help in the troubleshooting. In this my blog, I'm going to share a PHP script with some example.
Prerequisites- 

  • Database Server's HostName
  • A Database Name
  • DB user / Password
  • Another System installed PHP
Step 1- Create a PHP Script
To create your PHP script in your terminal session create a new file using vi editors. 

$ vi db-test.php

Now, copy the script below and paste in your file.

$servername = "MySQL_Host";
$username = "
MySQL_UserName";
$password = "
MySQL_Password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

$ php db-test.php

Connected successfully Establish to Database Server Name: '192.168.10.11'

Replace all the highlighted text with your's details.
Step 2 - Run PHP Script to test Database connectivity. 
There is two way to run your PHP script. 
1- One you can run from the terminal followed by this command. 

$ php db-test.php

If your connection to DB server is successful, you will get output like this. 

2- You can place db-test.php file in your Apache document root folder and call this script using the web browser. 
If your remote server has access to the DB server then you Browser output will be like this.

You have successfully tested Database connectivity using PHP script.