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
<?php $servername = "localhost"; $username = "root"; $password = ""; try { $conn = new PDO("mysql:host=$servername;dbname=firstdb", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_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.
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
<html> <head> <title>Insert data into database using php, mysql</title> </head> <body> <center> <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> <?php include 'connect.php'; if(isset($_POST['subbtn'])) { $name=$_POST['name']; $email=$_POST['email']; $contact=$_POST['contact']; $sql = "INSERT INTO users (name, email, contact) VALUES ('$name', '$email', '$contact')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully"; } ?> </form> </center> </body> </html>
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.
Lets check the database now. You’ll see the new entry has been created in it as follows.
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.