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

$servername = "localhost";
$username = "root";
$password = "";

try {
$conn = new PDO("mysql:host=$servername;dbname=firstdb", $username, $password);
// set the PDO error mode to exception
catch(PDOException $e)
echo "Connection failed: " . $e->getMessage();

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

<title>Insert data into database using php, mysql</title>
<h1>Insert data into database using php, mysql</h1>
<form action="import.php" method="post">
<input type="text" name="name" placeholder="Enter Name" method="post"/></br></br>
<input type="text" name="email" placeholder="Enter Email" method="post"/></br></br>
<input type="text" name="contact" placeholder="Enter Contact No." method="post"/></br></br>
<input type="submit" name="subbtn" value="Submit" method="post"/></br>

include 'connect.php';

if(isset($_POST['subbtn'])) {
$sql = "INSERT INTO users (name, email, contact) VALUES ('$name', '$email', '$contact')";
    // use exec() because no results are returned
    echo "New record created successfully";

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.