Create Database Connection File In PHP

Create a new php file and name it db_connnection.php and save it. Why am I creating a separate database connection file? Because if you have created multiple files in which you want to insert data or select data from the databases, you don’t need to write the code for database connection every time. You just have to include it by using PHP custom function include (include ‘connection.php’) on the top of your code and call its function and use it. It also helps when you are moving your project location from one PC to another and you have to change the values on the single file and all the changes will be applied to all the other files automatically. Write the following code in your db_connection file.

<?php
function OpenCon()
 {
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "1234";
 $db = "example";
 $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
 
 return $conn;
 }
 
function CloseCon($conn)
 {
 $conn -> close();
 }
   
?>

Here is the explanation of the variable that we have used in our db_connection file:

  1. $dbhost will be the host where your server is running it is usually localhost.
  2. $dbuser will be the username i.e. root and $dbpass will be the password which is the same that you used to access your phpmyadmin.
  3. $dbname will be the name of your database which we have created in this tutorial.

Create new php file to check your database connection

Create a new php file to connect to your database. name it index.php and add this code in this file.

<?php
include 'db_connection.php';
$conn = OpenCon();
echo "Connected Successfully";
CloseCon($conn);
?>

Run it!

Now open your browser and goto localhost/index.php and you should see this screen:

Leave a Reply

Your email address will not be published. Required fields are marked *