Site icon TestingDocs.com

Test MySQL Connection in PHP

Introduction

In this post, we will learn how to test MySQL connection in PHP using sample test code. In order to work with the MySQL database, we need to enable the extensions in the PHP configuration file.

MySQL Extensions

Enable MySQL extensions in the php.ini file.

https://www.testingdocs.com/enabling-mysql-extensions-in-php/

PHP INFO

echo phpinfo();

The above statement would display the PHP environment and configuration 
parameters.

Test PHP Code

Add a Sample PHP file under the Apache server htdocs directory.

MySQLDBConTest.php

<?php
/*************************************************************************
* This is to test PHP MySQL Connection
*
* www.TestingDocs.com
*************************************************************************/
$MySQLDb = new mysqli("localhost", "root", "<password>", "world");
if($MySQLDb->connect_errno)
{
     echo $MySQLDb>connect_error;
}
else
{
    echo "MySQL connection succeeded.";
}
?>

 

Screenshot

 

Verify

Once you added the test code file. Restart the Apache server. Browse the URL in the browser. For Example:

http://localhost/MySQLDBConTest.php

The output should be displayed as  “MySQL connection succeeded.”

 

That’s it. We have successfully tested MySQL database connection.

 

PHP Tutorials

PHP Tutorials on this website:

https://www.testingdocs.com/php-tutorials/

More Information on PHP

https://www.php.net/

Exit mobile version