Thursday 3 November 2016

Database Connection in PHP | How to create connection in php with database

Database Connection in PHP


Php support many types of database like SQL,MySQL,Oracle and other Microsoft database such as ODBC etc.

To create a connection to database with the help of PHP.You must have a server installed locally or remotely.If you buy web hosting on the internet you must know the database host name and password to connect to the database you created on that server.

Or if you don't have such type hosting you can make your computer as a server for this you have to install the server on your local computer.

To know how to make your Computer as server Please Follow the Link below:



Here I'm using Wamp Server as the server on my computer.
After installing server on your computer.Open your web browser and type the following: localhost/phpmyadmin

1.This will open the server admin panel of your wamp server.

2.Now Click on New Option in the left sidebar to create a new database.It will ask you for describing the database name,give a name to it.


Database connection in PHP
Database connection in PHP

3.Now click on "User" tab on top of this page and click on "Add user" below to add a user.


Database connection in PHP
Database connection in PHP

4.Now,fill the Login Information
   username: as your choice
   Host :localhost
   password: as you want

and check option:Grant all privileges on wildcard name (username\_%).
also, click on "Check all" option below it.
and now click on "Go" button. 


Database connection in PHP
Database connection in PHP

After this, we have to create a php file to connect to that database.
Open any Text Editor like Notepad,EditPlus,Notepad++ etc.
Add the following code to PHP file


Database connection in PHP
Database connection in PHP

In the above image, we use $conn variable to make connection
$conn=mysqli_connect("127.0.0.1","test","test","php_test");
means: 
$variable=mysqli_connect("host-name","username","password","database-name");

host-name=localhost or 127.0.0.1 any localhost address
username=your username
password=your password
database-name=name of your database
if all things are right then the connection will be Ok

>Database connection in PHP
Database connection in PHP


If you put wrong information in connection variable then it will create an error like the below example we change the database name with the wrong database name.


Database connection in PHPDatabase connection in PHP
Output Will be with Error


Database connection in PHP
Database connection in PHP

No comments:

Post a Comment

Leave a Reply!