Insert data into database using php, mysql

Hey Technoz! We have covered how to create database in mysql and Connectivity using php code. Now, we’re going to see how to create tables, how to insert data values in it and how to retrieve these values.

Now, Lets create the database named “firstdb“.

Connect with Database

So, first we have to connect with the db. For that purpose, we are creating the following file as connect.php

The connection method we have used here is newly introduced object oriented PDO approach. We are using it because it is more secure and prevents SQL injections.

Now, create a table named “users” with the three credentials as id,name,email and contact as shown below.
insert data into database using php mysql

Now, our data format is ready. We have to create the php file to insert data in table. Create the new file as import.php and paste the following code in it.

Insert Data

The above code contains the front UI and php code which is triggered by button click  event. As soon as the button is clicked, the values in the text boxes of both name and email are retrieved and inserted into the database using an SQL query.

Now we’re done. You can see the page at url: http://localhost/abc/import.php  fill all the details and hit submit. The confirmation message will appear as shown ion following image.

insert data into database using php mysql

Lets check the database now. You’ll see the new entry has been created in it as follows.

insert data into database using php mysql

It’s working fine. Meet you in next tutorial

Download Source Code

If you have any problems in implementing above tutorial, you can download source code from below link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.