How to connect database using PHP and MySQL

How to connect database using PHP and MySQL

In this blog, you will learn how to start managing database using PHP and also you will learn how to use PHP to insert into Mysql database. Before we proceed to connect PHP to a database you should gain access to your hosting control panel we are using cPanel for this purpose.

1 Create a Mysql database

You have to create a database on Mysql database section. After creating Mysql database on cPanel it will look like given below.

How to connect database using PHP and MySQL

Once you created the Mysql database then enter all required details for creating a new user in the database.

mysql insert into table

The important thing you should note down the username and password because this details you will need in the next step.

2. Create a table:-

Visit phpMyAdmin for creating a table. We will create a table named Customer for our database. You can also create a new table by clicking create table button. After entering all the details your table looks like given below.

php insert data into MySQL

3. Writing PHP code for connecting to Mysql database:-

There are two types to connect an SQL database with PHP that are MySQLi and PDO. We will go throw MySQLi where this is stands for MySQL Improved. This MySQLi introduce a new feature to the MySQL interface especially.                                                                                              So here is basic PHP code example which is used to establish a connection to MySQL database using MySQLi.

php mysqli

We require four variable to establish a proper connection: $servername, $database, $username and $password.

A function die() is executed here which is basically used for killing our script and gives us a message that we have set. So this will by default say Connection failed.

4. Successfully record inserted:-

once you created the successful connection to the database you can see recorded value is displayed such as given below.

insert into database php



Leave a Reply

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