Good Solution to display a table on button click in PHP

0
301
Good Solution to display a table on button click in PHP
Good Solution to display a table on button click in PHP

In this article, you going to see the best solution to display a table on button click in PHP. We going to do this in the simplest way.

To display table, obviously we required records which is going to get from database.

Let’s start with topic to display table in PHP step by step.

First you have to create database in MySQL. In that database create table called employ.

Below is the example for CREATE STATEMENT to create table in database.

So execute SQL query for creating table in database.

CREATE TABLE `employ` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After executing this above query a table is created in database.

TABLE CREATED
TABLE CREATED

As we need a number of records so that it can be shown in the table, to achieve this we need to insert records in database table called employ.

To insert record, then we have to execute INSERT STATEMENT query.

Below is example for insert SQL query statement.

INSERT INTO `employ` (`id`, `name`, `email`, `phone`, `created_at`) VALUES
(1, 'Rocky', 'rocky@gmail.com', '9898989988', '2020-06-21 04:44:13'),
(2, 'somo', 'somo@gmail.co', '9898989912', '2020-06-13 18:30:00');

After executing above SQL query, data get inserted in database table.

INSERTED RECORD
INSERTED RECORD

To understand more about Sql you check with this link MySQL query.

Now next important step is to display the record in table.

To achieve this we going to do AJAX.

From below script you come to know each and every thing regarding to display data in the table.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Display table in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <style>
table, td{
	width:300px;
	text-align:center;
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  padding:5px;
}
</style>
</head>
<body>
<input class="title" type="text" name="title" id="title" placeholder="name"/>
<button class="btnSearch" name="btnSearch" id="btnSearch" >Get Table Data</button>
<!-- This div will contain a list of all jobs that match our search term -->
<div id="search_results" style="padding:5px;"></div>
<script type="text/javascript">
$(document).ready(function() {
    //Add a JQuery click listener to our search button.
    $('#btnSearch').click(function(){
        //get the titlesearch that is being search for
        //from the search_box.
        var titlesearch = $('#title').val().trim();
        //Carry out a GET Ajax request using JQuery
        $.ajax({
            //The URL of the PHP file that searches MySQL.
            url: 'getdata.php',
            data: {
                titlesearch: titlesearch  
            },
            success: function(returnData){
                $('#search_results').html('');
                //Parse the JSON that we got back from search.php
                var results = JSON.parse(returnData);
                //Loop through our employee array and append their
                //names to our search results div.
                $.each(results, function(key, value){
			    $('#search_results').append("<table >");
				$('#search_results').append("<tr>");
				$('#search_results').append("<th>Name");
				$('#search_results').append("</th>");
				$('#search_results').append("<th>Email");
				$('#search_results').append("</th>");
				$('#search_results').append("<th>Phone");
				$('#search_results').append("</th>");
				$('#search_results').append("</tr>");
			    $('#search_results').append("<tr>");
				$('#search_results').append("<td>"+value.name+"</td>");
				$('#search_results').append("<td>"+value.email+"</div>");
				$('#search_results').append("<td>"+value.phone+"</div>");
				$('#search_results').append("</tr>");
				$('#search_results').append("</table>");
                });
                //If no employees match the name that was searched for, display a
                //message saying that no results were found.
                if(results.length == 0){
                    $('#search_results').html("<div class='divtitle'>No Jobs with that name were found!</div></br>");
                }
            }
        });
     });
});
</script>
</body>
</html>

As you see in the above script there is a button, on click of this we going to use Ajax for getting data from database.

To get record from database we passing URL using Ajax.

It is the URL of file in which i have added the script for fetching record from database table.

Below is the script file in which i am executing the SELECT STATEMENT SQL query to get a record from the database table.

File named getdata.php

<?php 
//MySQL username.
$dbUser = 'root';
 
//MySQL password.
$dbPassword = '';
 
//MySQL host / server.
$dbServer = 'localhost';
 
//The MySQL database your table is located in.
$dbName = 'phpdatabase';
 
//Connect to MySQL database using PDO.
$pdo = new PDO("mysql:host=$dbServer;dbname=$dbName", $dbUser, $dbPassword);
 
//Get the name that is being searched for.
$titlesearch = isset($_GET['titlesearch']) ? trim($_GET['titlesearch']) : '';

 
//The simple SQL query that we will be running.
$sql = "SELECT * FROM `employ` WHERE `name` LIKE :titlesearch";
 
//Add % for wildcard search!
$titlesearch = "%$titlesearch%";
 
//Prepare our SELECT statement.
$statement = $pdo->prepare($sql);
 
//Bind the $name variable to our :name parameter.
$statement->bindValue(':titlesearch', $titlesearch);

//Execute the SQL statement.
$statement->execute();
 
//Fetch our result as an associative array.
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
 
//Echo the $results array in a JSON format so that we can
//easily handle the results with JavaScript / JQuery
echo json_encode($results);
?>

After executing of above script file on click of button the output is display as follow as.

OUTPUT
OUTPUT

I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.