PHP MySQL Connection Simple Way

MySQL database connection file/Program  is very impotent to connect PHP with MySQL server.  As a common practice if you have same database connection on each PHP page, you can place PHP MySQL connection file/Program in one common place for example in Root Directory.  
After placing connection file/ Program you can access connection on each page like below
I have created PHP file with name config.php and placed it in root directory. 

$servername = "localhost"; // Your server host name
$username = "admin"; // Your server Login ID or Name
$password = "password"; // Your server Login Password.
$dbname = "mySQLDB"; // Your MySQL server database
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
return $con;

Access config.php file from root directory:
To establish PHP and MySQL database connection use below line of code.

<?php  require_once($_SERVER['DOCUMENT_ROOT'] ."/config.php");?>

Note: $_SERVER['DOCUMENT_ROOT'] : This variable used to access the root directory path.

Please do not include file like below -

<?php  require_once("");?>

Its unsecured way to use files from server and this may not work as its required special permission from php.ini file. But, this is not recommended as this can lead to attack on your server by means of viruses, hackers, malware, SQL injections etc., so please don’t use this option unless you are not sure.

Final Code:

 <?php require_once($_SERVER['DOCUMENT_ROOT'] ."/config.php");?>   
 <!DOCTYPE html>  
 <title>Compamny Page</title>  
 <h1>This is my Profile Page</h1>  
 <div >  
 <?php // MySQL connection string  
 $query = "SELECT * FROM employee_table where employeeName='Michale Bode'";  
 //$query = "SELECT * FROM company_table where employeeName='".strtolower($empName)."'";  
 $result = mysqli_query($con, $query);  
 while($row = mysqli_fetch_array($result))  
  echo "<span> Employee Name :". $row['eFullName']. "<span><br>";  
  echo "<span> Employee ID :". $row['eID']. "<span><br>";  
  echo "<span> Employee Mobile :". $row['eMobile']. "<span><br>";  
  echo "<span> Employee Address :". $row['eAddress']. "<span><br>";  

Output :

This is my Profile Page

Employee Name: Michael S. Bode
Employee ID: A77199
Employee Mobile: +1 952-888-xxxx
Employee Address: 421 American Blvd E, Bloomington, MN 55425, USA

No comments :