Retrieve the data from mysql database using php

Welcome to this tutorial! In the last post, we’ve covered the basics of how to insert data in mysql database using php and simple html form. Now in this tutorial, we are going to discuss how to retrieve this data and make visible to user.

If you haven’t gone to the previous tutorial, you can go by clicking here.

We’ll use all the php files, databases from the previous tutorial.

<html>
<head>
<title>Insert data using php</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>

Retrieve Data

Now, we’ve to retrieve the data from our database using the following php file.

<html>
<head>
<title>Retrieve data from mysql database using php</title>
</head>
<body>
<center>
<h1>Insert data into database using php, mysql</h1>
<form action="display.php" method="post">
<input type="text" name="id" placeholder="Enter ID" method="post"/>
<input type="submit" name="subbtn" value="Submit" method="post"/></br>

<?php	
if(isset($_POST['subbtn'])) {
	
$con=mysqli_connect("localhost","root","","firstdb");
    // Check connection
    if (mysqli_connect_errno())
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

$id=$_POST['id'];

//Getting Name
	$result = $con->query("SELECT name FROM users WHERE id=$id")
        or trigger_error($con->error);
        $name = $result->fetch_array(MYSQL_BOTH);
        echo "<br/>Name: ".$name['name'];
}
?>
</form>
</body>
</html>

We’re here using the mysqli_connect() procedure to connect with the database as it becomes an easy task to retrieve the data using “SELECT” query. the isset() function is applied on a button which is executed after the button click and performs the code written in the curly brackets.
Now, run the project. You’ll see the following image with the name value of the respective id of the entry.

 

data retrieve

That’s it! It is working fine. Thanks for  watching this 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.