Author

Ankit Prajapati

Browsing

The pie chart is the most important part of data visualization. If you are looking for the code to draw the dynamic pie chart according to your data then you are in the right place.

Our website Coding Birds Online provides the very simple, to the point and 100% working source code with a complete guide. You can check this demo also.

What is a pie chart?

A pie chart (or a circle chart) is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents. You can read more about this chart from here.

coding-birds-online-what-is-pie-chart-exmple-image

Why it is used?

If you are using a web application or website or any report generation software then you might have noticed this feature. Graphical or visual representation of data is usually a requirement for this software.

For example, You are using an ERP system of any college you might have seen your attendance in pie chart. If you are making any software for attendance management, then it will be a great feature to that.

Starting to Code 🙂

Sounds interesting? I know surely you are. Now that’s enough to understand. So what are you waiting for? let’s get started. Visit highcharts.com for reference. If you click on this link, it will give you the same code but with static data.

  • Create an HTML page (index.php) to display the pie chart
  • Get the required imports like JavaScripts to draw a pie chart
  • Paste these imports to the head tag of the index file.
  • Paste the javaScript code above the closing tag of the body.

These are the required imports to create a dynamic pie chart.

 <script src="https://code.highcharts.com/highcharts.js"></script>
 <script src="https://code.highcharts.com/modules/exporting.js"></script>
 <script src="https://code.highcharts.com/modules/export-data.js"></script>
 <script src="https://code.highcharts.com/modules/accessibility.js"></script>

Step 1: Create index.php file

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
    <title>How to create dynamic pie chart - Coding Birds Online</title>
    <style> .center-block { display: block;margin-left: auto;margin-right: auto; }</style>
</head>
<body>
<div class="container">
    <center>
        <div id="container"></div>
    </center>
    <img class="center-block" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" width="50">
 </div>
<?php
include "config.php"; // connection file with database
$query = "SELECT * FROM bird_pie_chart"; // get the records on which pie chart is to be drawn
$getData = $connection->query($query);
?>
<script>
    // Build the chart
    Highcharts.chart('container', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Programming Language Popularity, 2020'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        accessibility: {
            point: {
                valueSuffix: '%'
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: 'Popularity',
            colorByPoint: true,
            data: [
                <?php
                $data = '';
                if ($getData->num_rows>0){
                    while ($row = $getData->fetch_object()){
                        $data.='{ name:"'.$row->programming.'",y:'.$row->popularity.'},';
                    }
                }
                echo $data;
                ?>
            ]
        }]
    });
</script>
</body>
</html>

In this file, I am including a config.php, which is a connection file to the database. I am fetching records from the bird_pie_chart table. Don’t worry, I will provide the complete source code. The following is the database table structure.

coding-birds-online-table-structure

In this example, I am showing you a comparison of programming languages, with dummy data. This is now the actual data. You can customize this code and database table according to your needs.

Step 2: Run the code to get the desired output !!! That’s it.

Output

when you run the code and make sure everything is fine, then you will get the same output as following.

how-to-make-a-dynamic-pie-chart-in-php-in-2-steps-sample-output

Source Code & Demo to make a dynamic pie chart

You can download the full 100% working source code from here. You check this demo also.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Happy Coding 🙂

Hi, If you are looking to give a dynamic search feature to your web application or your web project, without any problems, then you are in the right place.

This website Coding Birds Online provides the very simple, to the point and 100% working source code with a complete guide. You can check this demo also.

What is the DataTables plugin?

DataTable is a plug-in for the jQuery JavaScript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table. You can read more about DataTable from the official website.

Not understood? Don’t worry, I will explain. In simple words. It is a simple plugin or tool we can say, that helps us to search the records in a larger table with very little time and without page refresh.

For example, check this screenshot when type any keyword in the search box, the results are dynamically displayed.

coding-birds-online-how-to-integrate-data-table-plugin-in-html-and-css-output-on-search

Why we need DataTables?

If you are using a web application, then you might have a reporting feature. You can learn how to export records. Sometimes you want to search any data in the table, if normally you code then you search a keyword in the search box, the page will be reloaded and then you will get the desired record.

Sounds interesting? I know surely you are. Now that’s enough to understand. So what are you waiting for? let’s get started

Steps to integrate data table plugin

  • Load the jQuery 1st, In the head tag of index.php file.
  • Now load the required JavaScripts provided by DataTable plugin.
  • You can load bootstrap to style the tables, It is optional.
  • Create a table in the index.php file.
  • Now add a two-line of jQuery Code.
  • Test it !!!

Let’s create the index.php or index.html, You can use index.php to fetch the records from the database. Here I am creating a static table. You can learn how to fetch records in JAVA & Servlets.

Add these imports to your head tag of the page on which you want to integrate the DataTable plugin. Make sure you import it in this sequence only.

 <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

 <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
 <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
 <script src="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css"></script>

Complete Code

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Integrate datatable - Coding Birds Online</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css"></script>

    <link   rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <style> #thead>tr>th{ color: white; } </style>
</head>
<body>
<div class="container">
    <table id="exampleTable" class="table table-striped table-bordered" style="width: 70%">
        <thead id="thead">
        <tr style="background-color: #1573ff">
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
        <tr>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>2009/01/12</td>
            <td>$86,000</td>
        </tr>
        <tr>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2012/03/29</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>2008/11/28</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>2012/12/02</td>
            <td>$372,000</td>
        </tr>
        <tr>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>2012/08/06</td>
            <td>$137,500</td>
        </tr>
        <tr>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
            <td>2010/10/14</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>2009/09/15</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>2008/12/13</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>30</td>
            <td>2008/12/19</td>
            <td>$90,560</td>
        </tr>
        <tr>
            <td>Quinn Flynn</td>
            <td>Support Lead</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2013/03/03</td>
            <td>$342,000</td>
        </tr>
        <tr>
            <td>Charde Marshall</td>
            <td>Regional Director</td>
            <td>San Francisco</td>
            <td>36</td>
            <td>2008/10/16</td>
            <td>$470,600</td>
        </tr>
        <tr>
            <td>Haley Kennedy</td>
            <td>Senior Marketing Designer</td>
            <td>London</td>
            <td>43</td>
            <td>2012/12/18</td>
            <td>$313,500</td>
        </tr>
        <tr>
            <td>Tatyana Fitzpatrick</td>
            <td>Regional Director</td>
            <td>London</td>
            <td>19</td>
            <td>2010/03/17</td>
            <td>$385,750</td>
        </tr>
        <tr>
            <td>Michael Silva</td>
            <td>Marketing Designer</td>
            <td>London</td>
            <td>66</td>
            <td>2012/11/27</td>
            <td>$198,500</td>
        </tr>
        <tr>
            <td>Paul Byrd</td>
            <td>Chief Financial Officer (CFO)</td>
            <td>New York</td>
            <td>64</td>
            <td>2010/06/09</td>
            <td>$725,000</td>
        </tr>
        <tr>
            <td>Gloria Little</td>
            <td>Systems Administrator</td>
            <td>New York</td>
            <td>59</td>
            <td>2009/04/10</td>
            <td>$237,500</td>
        </tr>
        <tr>
            <td>Bradley Greer</td>
            <td>Software Engineer</td>
            <td>London</td>
            <td>41</td>
            <td>2012/10/13</td>
            <td>$132,000</td>
        </tr>
        <tr>
            <td>Dai Rios</td>
            <td>Personnel Lead</td>
            <td>Edinburgh</td>
            <td>35</td>
            <td>2012/09/26</td>
            <td>$217,500</td>
        </tr>
        <tr>
            <td>Jenette Caldwell</td>
            <td>Development Lead</td>
            <td>New York</td>
            <td>30</td>
            <td>2011/09/03</td>
            <td>$345,000</td>
        </tr>
        <tr>
            <td>Yuri Berry</td>
            <td>Chief Marketing Officer (CMO)</td>
            <td>New York</td>
            <td>40</td>
            <td>2009/06/25</td>
            <td>$675,000</td>
        </tr>
        <tr>
            <td>Caesar Vance</td>
            <td>Pre-Sales Support</td>
            <td>New York</td>
            <td>21</td>
            <td>2011/12/12</td>
            <td>$106,450</td>
        </tr>
        <tr>
            <td>Doris Wilder</td>
            <td>Sales Assistant</td>
            <td>Sydney</td>
            <td>23</td>
            <td>2010/09/20</td>
            <td>$85,600</td>
        </tr>
        <tr>
            <td>Angelica Ramos</td>
            <td>Chief Executive Officer (CEO)</td>
            <td>London</td>
            <td>47</td>
            <td>2009/10/09</td>
            <td>$1,200,000</td>
        </tr>
        <tr>
            <td>Gavin Joyce</td>
            <td>Developer</td>
            <td>Edinburgh</td>
            <td>42</td>
            <td>2010/12/22</td>
            <td>$92,575</td>
        </tr>
        <tr>
            <td>Jennifer Chang</td>
            <td>Regional Director</td>
            <td>Singapore</td>
            <td>28</td>
            <td>2010/11/14</td>
            <td>$357,650</td>
        </tr>
        <tr>
            <td>Brenden Wagner</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>28</td>
            <td>2011/06/07</td>
            <td>$206,850</td>
        </tr>
        <tr>
            <td>Fiona Green</td>
            <td>Chief Operating Officer (COO)</td>
            <td>San Francisco</td>
            <td>48</td>
            <td>2010/03/11</td>
            <td>$850,000</td>
        </tr>
        <tr>
            <td>Shou Itou</td>
            <td>Regional Marketing</td>
            <td>Tokyo</td>
            <td>20</td>
            <td>2011/08/14</td>
            <td>$163,000</td>
        </tr>
        <tr>
            <td>Michelle House</td>
            <td>Integration Specialist</td>
            <td>Sydney</td>
            <td>37</td>
            <td>2011/06/02</td>
            <td>$95,400</td>
        </tr>
        <tr>
            <td>Suki Burks</td>
            <td>Developer</td>
            <td>London</td>
            <td>53</td>
            <td>2009/10/22</td>
            <td>$114,500</td>
        </tr>
        <tr>
            <td>Prescott Bartlett</td>
            <td>Technical Author</td>
            <td>London</td>
            <td>27</td>
            <td>2011/05/07</td>
            <td>$145,000</td>
        </tr>
        <tr>
            <td>Gavin Cortez</td>
            <td>Team Leader</td>
            <td>San Francisco</td>
            <td>22</td>
            <td>2008/10/26</td>
            <td>$235,500</td>
        </tr>
        <tr>
            <td>Martena Mccray</td>
            <td>Post-Sales support</td>
            <td>Edinburgh</td>
            <td>46</td>
            <td>2011/03/09</td>
            <td>$324,050</td>
        </tr>
        <tr>
            <td>Unity Butler</td>
            <td>Marketing Designer</td>
            <td>San Francisco</td>
            <td>47</td>
            <td>2009/12/09</td>
            <td>$85,675</td>
        </tr>
        <tr>
            <td>Howard Hatfield</td>
            <td>Office Manager</td>
            <td>San Francisco</td>
            <td>51</td>
            <td>2008/12/16</td>
            <td>$164,500</td>
        </tr>
        <tr>
            <td>Hope Fuentes</td>
            <td>Secretary</td>
            <td>San Francisco</td>
            <td>41</td>
            <td>2010/02/12</td>
            <td>$109,850</td>
        </tr>
        <tr>
            <td>Vivian Harrell</td>
            <td>Financial Controller</td>
            <td>San Francisco</td>
            <td>62</td>
            <td>2009/02/14</td>
            <td>$452,500</td>
        </tr>
        <tr>
            <td>Timothy Mooney</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>37</td>
            <td>2008/12/11</td>
            <td>$136,200</td>
        </tr>
        <tr>
            <td>Jackson Bradshaw</td>
            <td>Director</td>
            <td>New York</td>
            <td>65</td>
            <td>2008/09/26</td>
            <td>$645,750</td>
        </tr>
        <tr>
            <td>Olivia Liang</td>
            <td>Support Engineer</td>
            <td>Singapore</td>
            <td>64</td>
            <td>2011/02/03</td>
            <td>$234,500</td>
        </tr>
        <tr>
            <td>Bruno Nash</td>
            <td>Software Engineer</td>
            <td>London</td>
            <td>38</td>
            <td>2011/05/03</td>
            <td>$163,500</td>
        </tr>
        <tr>
            <td>Sakura Yamamoto</td>
            <td>Support Engineer</td>
            <td>Tokyo</td>
            <td>37</td>
            <td>2009/08/19</td>
            <td>$139,575</td>
        </tr>
        <tr>
            <td>Thor Walton</td>
            <td>Developer</td>
            <td>New York</td>
            <td>61</td>
            <td>2013/08/11</td>
            <td>$98,540</td>
        </tr>
        <tr>
            <td>Finn Camacho</td>
            <td>Support Engineer</td>
            <td>San Francisco</td>
            <td>47</td>
            <td>2009/07/07</td>
            <td>$87,500</td>
        </tr>
        <tr>
            <td>Serge Baldwin</td>
            <td>Data Coordinator</td>
            <td>Singapore</td>
            <td>64</td>
            <td>2012/04/09</td>
            <td>$138,575</td>
        </tr>
        <tr>
            <td>Zenaida Frank</td>
            <td>Software Engineer</td>
            <td>New York</td>
            <td>63</td>
            <td>2010/01/04</td>
            <td>$125,250</td>
        </tr>
        <tr>
            <td>Zorita Serrano</td>
            <td>Software Engineer</td>
            <td>San Francisco</td>
            <td>56</td>
            <td>2012/06/01</td>
            <td>$115,000</td>
        </tr>
        <tr>
            <td>Jennifer Acosta</td>
            <td>Junior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>43</td>
            <td>2013/02/01</td>
            <td>$75,650</td>
        </tr>
        <tr>
            <td>Cara Stevens</td>
            <td>Sales Assistant</td>
            <td>New York</td>
            <td>46</td>
            <td>2011/12/06</td>
            <td>$145,600</td>
        </tr>
        <tr>
            <td>Hermione Butler</td>
            <td>Regional Director</td>
            <td>London</td>
            <td>47</td>
            <td>2011/03/21</td>
            <td>$356,250</td>
        </tr>
        <tr>
            <td>Lael Greer</td>
            <td>Systems Administrator</td>
            <td>London</td>
            <td>21</td>
            <td>2009/02/27</td>
            <td>$103,500</td>
        </tr>
        <tr>
            <td>Jonas Alexander</td>
            <td>Developer</td>
            <td>San Francisco</td>
            <td>30</td>
            <td>2010/07/14</td>
            <td>$86,500</td>
        </tr>
        <tr>
            <td>Shad Decker</td>
            <td>Regional Director</td>
            <td>Edinburgh</td>
            <td>51</td>
            <td>2008/11/13</td>
            <td>$183,000</td>
        </tr>
        <tr>
            <td>Michael Bruce</td>
            <td>Javascript Developer</td>
            <td>Singapore</td>
            <td>29</td>
            <td>2011/06/27</td>
            <td>$183,000</td>
        </tr>
        <tr>
            <td>Donna Snider</td>
            <td>Customer Support</td>
            <td>New York</td>
            <td>27</td>
            <td>2011/01/25</td>
            <td>$112,000</td>
        </tr>
        </tbody>
        <tfoot>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
        </tfoot>
    </table>
</div>
<script>
    $(document).ready(function() {
        $('#exampleTable').DataTable();
    } );
</script>
</body>
</html>

Final output

coding-birds-online-how-to-integrate-data-table-plugin-in-html-and-css-screen-output

Source Code with Demo

To download the full working source code download it from here. You can check this demo also.

You can also watch this video of mine, uploaded a year ago explaining the same.

Conclusion

I hope you learned everything I explained above, If you have any suggestions, are appreciated. And if you have any error comment here. If you want to download the source code then click here.

Happy Coding 🙂

Hello, beginners and coders, are you looking for the PHP script to export data from MySQL table to Excel file in PHP, then you are right place. Coding Birds Online is a website that provides 100% working source code. You can check this demo.

Importance & Need for this?

Exporting table data to excel is simply a reporting feature that every web application or web project needs it. Suppose you are using a web application that registers hundreds of employees a day. But unfortunately, you might not now, your application may crash or any bug can occur.

So it is always a good practice to give an option to export the complete detail of registred employees to the excel sheet so that we can have a backup. This is what we are going to code this feature in PHP. So what are you waiting for? let’s get started.

So here are the files and folders that you need to code this feature.

coding-birds-online-export-data-from-mysql-table-to-excel-file-in-php-files-and-folders
  • index.php file is the main file that shows the records from the database and has an export button.
  • export-table-script.php, this is the actual logic file that export data to excel file.
  • Common.php is the class file that fetches all the records from the database.
  • config.php is the connection file to the database.
  • bird_records.sql is the SQL table in the database, I will provide it.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Export table data to csv file in php - Coding Birds Online</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="validation.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <style>
        #thead>tr>th{ color: white; }
    </style>
</head>
<body>
<div style="margin-top: 20px;padding-bottom: 20px;">
    <center>
        <img width="100" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"/>
        <h3>Export table data to csv file in php</h3>
    </center>
</div>
<div class="container">
    <form action="export-table-script.php" method="post">
        <table class="table table-bordered table-condensed">
            <thead id="thead" style="background-color:#ff195a">
            <tr>
                <th>Sr.No</th>
                <th>Name</th>
                <th>Class</th>
                <th>Total Markes</th>
                <th>Gender</th>
            </tr>
            </thead>
            <tbody>
            <?php
            include "config.php";
            include_once "Common.php";
            $common = new Common();
            $records = $common->getAllRecords($connection);
            if ($records->num_rows>0){
                $sr = 1;
                while ($record = $records->fetch_object()) {
                    $recordId = $record->id;
                    $name = $record->name;
                    $class = $record->class;
                    $marks = $record->marks;
                    $gender = $record->gender;?>
                    <tr>
                        <td><?php echo $sr;?></td>
                        <td><?php echo $name;?></td>
                        <td><?php echo $class;?></td>
                        <td><?php echo $marks;?></td>
                        <td><?php echo $gender;?></td>
                    </tr>
                    <?php
                    $sr++;
                }
            }
            ?>
            </tbody>
        </table>
        <button type="submit" name="exportBtn" id="exportBtn" class="btn btn-primary"style="float: right">Export Data</button>
    </form>
</div>
</body>
</html>

export-table-script.php

<?php
include "config.php";
include_once "Common.php";
$common = new Common();
$records = $common->getAllRecords($connection);
$dataTable = '';
$dataTable .='<table class="table">
                   <thead>
                       <tr>
                            <th>Sr.No</th>
                            <th>Name</th>
                            <th>Class</th>
                            <th>Total Markes</th>
                            <th>Gender</th>
                        </tr>
                    </thead>
                    <tbody>';
    if ($records->num_rows>0) {
        $sr = 1;
        while ($record = $records->fetch_object()) {
            $recordId = $record->id;
            $name = $record->name;
            $class = $record->class;
            $marks = $record->marks;
            $gender = $record->gender;
            $dataTable .='
            <tr>
                <td>'.$sr.'</td>
                <td>'.$name.'</td>
                <td>'.$class.'</td>
                <td>'.$marks.'</td>
                <td>'.$gender.'</td>
            </tr>';

            $sr++;
        }
    }
    $dataTable .= '  </tbody>
                    </table>';
    $filename = "exported-data-".date('d-m-Y H:i:s').".xls";
    header('Content-Type: application/xls');
    header('Content-Disposition: attachment; filename='.$filename);
    echo $dataTable;

config.php

<?php
$hostName = "localhost"; // host name
$username = "root";  // database username
$password = ""; // database password
$databaseName = "codingbirds"; // database name

$connection = new mysqli($hostName,$username,$password,$databaseName);
if (!$connection) {
    die("Error in database connection". $connection->connect_error);
}
?>

Common.php

<?php
class Common
{
    public function getAllRecords($connection) {
        $query = "SELECT * FROM bird_records";
        $result = $connection->query($query) or die("Error in query1".$connection->error);
        return $result;
    }
}

If you run this code you will get following out, the main home page and exported out also.

coding-birds-online-export-data-from-mysql-table-to-excel-file-in-php-screen-output

When you click the export button then the file will be download in excel format as like this.

coding-birds-online-export-data-from-mysql-table-to-excel-file-in-php-generated-output

Source Code

To download the full working source code download it from here.

Conclusion

I hope you learned everything I explained above, If you have any suggestions, are appreciated. And if you have any error comment here. If you want to download the source code then click here.

Hi, Are you looking to learn how to integrate Google re-Captcha with the easiest method, then you are in the right place. Coding Birds Online is a how-to, tutorial website which provides the easiest coding logic with full working source code. Check this demo.

What is Google re-Captcha?

reCAPTCHA is a free service provided by Google which helps to protect websites from spam and abuse. A “CAPTCHA” is a Turing test to tell humans and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. By adding reCAPTCHA to a site, you can block automated software while helping your welcome users to enter with ease.

Why we need it?

If you have a website or web application, you might have noticed that there are some unnecessary contact, inquiry entries came from contact form of the website. These entries are not by a human, so you might think then? The answer is these are by some bots and much other malicious software.

In previous days, we used to put a random number before the form submission and ask the user to enter the same number and verify it on the server-side. But now this method is old. Google’s reCAPTCHA is a new way to verify a user, and it is very simple to verify the user. They just need a single click or tap to prove they are not a robot.

Steps to implement google ReCaptcha in PHP

We need to get the API keys by registering our site, and then Google provides site key, secret key. These keys are important to display the Google re-Captcha and another one is to verify the same.

Step 1: Get re-CAPTCHA API key

In order to get the API keys, visit the https://www.google.com/recaptcha/admin and register your website. If you open this link and login with your Google account you will get a dashboard. Now click the 3rd button displaying like +.

coding-birds-online-how-to-integrate-google-re-captcha-with-php-getting-keys-by-register

Now you will get the API keys as

coding-birds-online-how-to-integrate-google-re-captcha-with-php-keys

Step 2: Adding re-CAPTCHA to your site

Insert this code to head tag of your HTML page

 <script src='https://www.google.com/recaptcha/api.js' async defer ></script>

Step 3: Create a FORM with re-Captcha

This is the main index.php file that is your output on the screen. It uses a verify-captcha.php file to validate the Google re-Captcha. To create these files, take a look.

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Google re-Captcha - Coding Birds Online</title>
    <script src='https://www.google.com/recaptcha/api.js' async defer ></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <h5 class="card-title text-center">Google re-Captcha</h5>
                    <form action="verify-captcha.php" method="post" id="reCaptchaForm" class="form-signin">
                        <div class="form-label-group">
                            <label for="inputEmail">Name<span style="color: #FF0000">*</span></label>
                            <input type="text" name="name" id="name" class="form-control" required placeholder="Name">
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">Email<span style="color: #FF0000">*</span></label>
                            <input type="text" name="email" id="email" class="form-control" required placeholder="Email">
                        </div> <br/>
                        <div class="form-label-group">
                            <div class="g-recaptcha" data-sitekey="your_site_key">
                            </div> <br/>
                            <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-lg btn-primary btn-block text-uppercase" >Verify</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

verify-captcha.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Google re-Captcha - Coding Birds Online</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <h5 class="card-title text-center">Google re-Captcha Result </h5>
                    <?php

                    if(isset($_POST['submitBtn'])) {
                        $secret = 'your_secret_key';
                        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
                        $responseData = json_decode($verifyResponse);

                        if($responseData->success)
                        {
                            echo ' <div class="alert alert-success" role="alert">
                                    Success ! Captcha Verified
                                   </div>';
                            echo $_POST['name']; echo '<br/>';
                            echo $_POST['email']; echo '<br/>';
                            echo 'Do whatever you want of this received data !';
                        }
                        else
                        {
                            echo ' <div class="alert alert-danger" role="alert">
                                        Please verify you are not robot !
                                    </div>';
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Step 4: Test out code

When you run this code you will get the output like this. You can check this working demo also. Click to see the demo.

coding-birds-online-how-to-integrate-google-re-captcha-with-php-out-screen

Now, these form fields are mandatory to fill. If you submit this form filling the fields without checking re-Captcha then you will get output like this.

coding-birds-online-how-to-integrate-google-re-captcha-with-php-output-failed

If you fill the form and verify you are not a robot, then you will see this.

coding-birds-online-how-to-integrate-google-re-captcha-with-php-output-success

Source Code

To download the full working source code download it from here.

Conclusion

I hope you learned everything I explained above, If you have any suggestions, are appreciated. And if you have any error comment here. If you want to download the source code then click here.

Hi, Are you looking for the PHP script of how to generate QR code in PHP code? then you are right place. Here I will provide the concept, and how to do this. As I think generating QR code with PHP is not complicated nor logical.

You can accomplish this task by using a plugin-play opensource PHP library. So don’t worry. Let’s take a quick introduction to what is the QR code. Check this demo.

What is QR Code?

QR code is the full form of the Quick Response Code 😂. It’s not a joke, I am saying true. You can google it. It is the 2D barcode format code it is used to store text like phone numbers, emails, address, and simple text, or anything want to store, you can.

How to generate QR code in PHP?

I will use a plugin-play opensource PHP library to perform this task. I will create a simple HTML form that accepts text, email, phone or any text for which you want to generate QR code. You can check this demo.

Steps to generate dynamic QR code in PHP

  • Create an index.php file, which is a simple HTML form to receive the text.
  • Make a generate-qr-script.php, which is a PHP script file to generate QR.
  • Create a generate-qr-js.js, which is responsible to generate dynamic QR without page reload.
  • And download the QR code library we talked above. Download it from here.
  • Finally,create a folder to save QR images. In my terms it is generated-qr.

Files and folder structure

how-to-generate-qr-code-in-php-coding-birds-online-files-and-folder-structure

Now its time to create these files, so what are you waiting for ? Let’s start

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Send Email Example</title>
    <style>
        .center-block {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <h5 class="card-title text-center">Generate QR Code</h5>
                    <form id="generateQrForm" class="form-signin">
                        <div class="form-label-group">
                            <label for="inputEmail">Text For QR <span style="color: #FF0000">*</span></label>
                            <input type="text" name="qrText" id="qrText" class="form-control" required placeholder="Enter something to generate QR">
                        </div> <br/>
                       <div id="generatedQr text-center">
                            <img src="" id="generatedQrImg" class="center-block">
                        </div> <br/>
                        <button type="submit" name="generateQrBtn" id="generateQrBtn" class="btn btn-lg btn-primary btn-block text-uppercase" >Generate QR</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="generate-qr-js.js"></script>
</body>
</html>

generate-qr-script.php

<?php
include "library/qrlib.php";
if (isset($_POST['generateQr']) == 'generateQr')
{
    $qrText = $_POST['qrText']; // receive the text for QR
    $directory = "generated-qr/"; // folder where to store QR
    $fileName = 'QR-'.rand().'.png'; // generate random name of QR image
    QRcode::png($qrText, $directory.$fileName, 'L', 4, 2); // library function to generate QR
    echo "success^".$directory.$fileName; // returns the qr-image path
}

generate-qr-js.js

$("form#generateQrForm").on("submit",function (e) {
    e.preventDefault();
   var qrText = $("#qrText").val();
   $.post("generate-qr-script.php",{generateQr:'generateQr',qrText:qrText},function (response) {
        var data = response.split('^');
        var generateQrImgPath = data[1];
        $("#generatedQrImg").attr("src",generateQrImgPath);
   })
});

PHP QR code library

Now you need to download the library. it is available in SourceForge. Download it from here.

Output you see

how-to-generate-qr-code-in-php-coding-birds-online-output-1

When you enter some text and hit generate QR button, you will get output like this without page reloading. I used jQuery, AJAX to make it.

how-to-generate-qr-code-in-php-coding-birds-online-output-2

Conclusion

So you learned about how to how to generate QR code with PHP using PHP library and HTML form. If you face any error comment here your problem, and if you want to download the full working source code then you can download it from here.

Happy Coding 🙂

Hi, are you looking for the code in which you want to delete the multiple records using a checkbox? In this tutorial, you will learn to delete multiple records in PHP using the checkbox or selected checkbox.

In the previous tutorial, you learned about how to delete a single record. Here you learn about to delete the multiple records by selected checkbox with validation to select at least one checkbox. Here are the files and folders to delete multiple records in PHP. Check this demo.

delete-multiple-records-in-php-using-the-checkbox-files-and-folder

So without wasting our time, let’s get started to create our files.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Delete records from database using PHP - Coding Birds Online</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="validation.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <style>
        #thead>tr>th{ color: white; }
    </style>
</head>
<body>
<div style="margin-top: 20px;padding-bottom: 20px;">
    <center>
        <img width="100" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"/>
        <h3>Delete multiple records from database using PHP </h3>
    </center>
</div>
<div class="container">
    <form action="delete-script.php" method="post">
    <table class="table table-bordered">
        <thead id="thead" style="background-color:#1573ff">
        <tr>
            <th>Sr.No</th>
            <th>Name</th>
            <th>Email</th>
            <th>Contact</th>
            <th>Department</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
        <?php
        include "config.php";
        include_once "Common.php";
        $common = new Common();
        $records = $common->getAllRecords($connection);
        if ($records->num_rows>0){
            $sr = 1;
            while ($record = $records->fetch_object()) {
                $recordId = $record->id;
                $name = $record->name;
                $email = $record->email;
                $contact = $record->contact;
                $department = $record->department;?>
                <tr>
                    <td><?php echo $sr;?></td>
                    <td><?php echo $name;?></td>
                    <td><?php echo $email;?></td>
                    <td><?php echo $contact;?></td>
                    <td><?php echo $department;?></td>
                    <td><input type="checkbox" name="recordsCheckBox[]" id="recordsCheckBox" value="<?php echo $recordId;?>"></td>
                </tr>
                <?php
                $sr++;
            }
        }
        ?>
        </tbody>
    </table>
        <input type="submit" name="deleteBtn" id="deleteBtn" class="btn btn-success" onclick="return validateForm();" value="Delete Records" style="float: right"/>
    </form>
</div>
</body>
</html>

This index.php file includes config.php and Common.php. These files are database connections and PHP class file. Let’s create these files.

config.php

<?php
$hostName = "localhost"; // host name
$username = "root";  // database username
$password = ""; // database password
$databaseName = "codingbirds"; // database name

$connection = new mysqli($hostName,$username,$password,$databaseName);
if (!$connection) {
    die("Error in database connection". $connection->connect_error);
}
?>

Common.php

<?php
class Common
{
    public function getAllRecords($connection) {
        $query = "SELECT * FROM bird_delete_records";
        $result = $connection->query($query) or die("Error in query1".$connection->error);
        return $result;
    }
    public function deleteRecordById($connection,$id) {
        $query = "DELETE FROM bird_delete_records WHERE id='$id'";
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result;
    }
}

validation.js

function validateForm() {
    var count_checked = $("[name='recordsCheckBox[]']:checked").length;
    if (count_checked == 0) {
        alert("Please check at least one checkbox");
        return false;
    }else{
        return true;
    }
}

delete-script.php

<?php
include "config.php";
include_once "Common.php";
if (isset($_POST['deleteBtn'])){
    $recordIds = $_POST['recordsCheckBox'];
    $common = new Common();
    foreach ( $recordIds as $id ) {
        $delete = $common->deleteRecordById($connection,$id);
    }
    if ($delete) {
        echo '<script>alert("Record deleted successfully !")</script>';
        echo '<script>window.location.href="index.php";</script>';
    }
}

After running this code you will get output like this.

delete-multiple-records-in-php-using-the-checkbox-output

So this is the output when you run the code. Now if you press the delete button when you get a prompt alert that, select at least one checkbox.

After selecting and pressing the delete button the records will be deleted that you have selected before. I hope you understood the concept and the code.

You can download the full working source code from here so that there is no error in your code. You can also watch this video uploaded a year ago of mine, telling the same thing but in procedural style.

Happy Coding 🙂

In a web application, 4 operations are mainly performed, Create,Read, Update and Delete. These are called CRUD operations in short.

  • Create – This is the first operation that is to save the data to the database.
  • Read – This is the operation to read or display the saved data from the database.
  • Update – This is to update the existing records in a database.
  • Delete – Last but not least, this is used to perform delete operation in the database.

Each operation has its own query to perform its task. Let’s take a look at each query and we will understand its concepts in our tutorials. But here we will talk about Delete operation only.

PHP | MySQL Delete Query

The DELETE query is used to delete records from the database table.
It is generally used along with the “Select” statement to delete only those records that satisfy a specific condition.

Syntax

DELETE FROM table_name WHERE column_value=condition

Example

Consider this following table named bird_delete_records has column names id, name, email, contact, and department.

how-to-delete-records-from-a-database-with-php-example-table

To delete the records we will write this query as given below.

DELETE FROM bird_delete_records WHERE id=1

Then what we are doing just putting our table name to query and make a condition. If any column satisfies the condition then we delete the record.

I hope you got the concept behind this. Now, let’s make our hands dirty with code. We need to create these files. Here are the files and folders.

how-to-delete-records-from-a-database-with-php-filesand-folder

So you got the files and folder. Now we will create these files.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Delete records from database using PHP - Coding Birds Online</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <style>
        #thead>tr>th{ color: white; }
    </style>
</head>
<body>
<div style="margin-top: 20px;padding-bottom: 20px;">
    <center>
        <img width="100" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"/>
        <h3>Delete records from database using PHP </h3>
    </center>
</div>
<div class="container">
    <table class="table">
        <thead id="thead" style="background-color: #26a2af">
        <tr>
            <th>Sr.No</th>
            <th>Name</th>
            <th>Email</th>
            <th>Contact</th>
            <th>Department</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
        <?php
        include "config.php";
        include_once "Common.php";
        $common = new Common();
        $records = $common->getAllRecords($connection);
        if ($records->num_rows>0){
            $sr = 1;
            while ($record = $records->fetch_object()) {
                $recordId = $record->id;
                $name = $record->name;
                $email = $record->email;
                $contact = $record->contact;
                $department = $record->department;?>
                <tr>
                    <th><?php echo $sr;?></th>
                    <th><?php echo $name;?></th>
                    <th><?php echo $email;?></th>
                    <th><?php echo $contact;?></th>
                    <th><?php echo $department;?></th>
                    <td><a href="delete-script.php?recordId=<?php echo $recordId?>" class="btn btn-danger btn-sm">Delete</a> </td>
                </tr>
                <?php
                $sr++;
            }
        }
        ?>
        </tbody>
    </table>
</div>
</body>
</html>

As you see the index.php file includes config.php and Common.php. These files are used to make the database connection and get records from the database and delete them, respectively. Create these files.

config.php

<?php
$hostName = "localhost"; // host name
$username = "root";  // database username
$password = ""; // database password
$databaseName = "codingbirds"; // database name

$connection = new mysqli($hostName,$username,$password,$databaseName);
if (!$connection) {
    die("Error in database connection". $connection->connect_error);
}
?>

Common.php

<?php
class Common
{
    public function getAllRecords($connection) {
        $query = "SELECT * FROM bird_delete_records";
        $result = $connection->query($query) or die("Error in query1".$connection->error);
        return $result;
    }

    public function deleteRecordById($connection,$recordId) {
        $query = "DELETE FROM bird_delete_records WHERE id='$recordId'";
        $result = $connection->query($query) or die("Error in query2".$connection->error);
        return $result;
    }
}

If you see index.php file and head over to where button we created we used delete-script.php?recordId=id. This is a query string variable when we use a question mark, a variable name is equal to value. This value will be received by delete-script.php to delete the records.

delete-script.php

<?php
include "config.php";
include_once "Common.php";
if (isset($_GET['recordId'])){
    $recordId = $_GET['recordId'];
    $common = new Common();
    $delete = $common->deleteRecordById($connection,$recordId);
    if ($delete){
        echo '<script>alert("Record deleted successfully !")</script>';
        echo '<script>window.location.href="index.php";</script>';
    }
}

In this file we are just creating an object of Common.php file, that is the class file. Here I have used the OOPs method. You can use procedural if you want. You can learn about oops from here.

Now its time to test our code. Is it working? surely it will work. Don’t worry, I will provide source code also. So this is the output when you run the code.

how-to-delete-records-from-a-database-with-php-output-screen

When you click the delete button then you will get this success alert message, that Record deleted successfully!. You can download the source code also. So that there is no possibility of errors.

how-to-delete-records-from-a-database-with-php-delete-success-output

If you have any problem then you watch this video also. I uploaded it on youtube a year ago. But explains the same thing but in procedural style.

Thanks for visiting this blog. I will see you in the next article.

Happy Coding 🙂

Hey! Are you looking to create a country-state-city select dropdown? Here I will give you a quick guide with source code so that you can implement it in your application in 0 errors. Check this demo.

I am Ankit and today I am gonna tell you about how you can code this select Dropdown in an easy way.
This dropdown is a dependency dropdown between the country, state, city. When one dropdown value depends upon another dropdown value then it is called dependent or dependency dropdown.

About Country-state-city dropdown

In this tutorial, we will create an HTML form with 3 select dropdowns. Which is Country, State, City respectively? To get states first I will select a country from the dropdown, and after that to get city I will select a state. This is how dependent dropdown works together. Don’t worry I will explain how to make them dependent on each other.

What are the requirements?

First of all, you need to have a number of countries in a country table in your database with a country id that is unique. 

Country Table

How-to-make country-state-city dropdown-in-PHP-country-table

State Table

Then after, you need to have a states table in your database with entries of various states and a column on country id, so that you can identify the state name by country id.

How-to-make country-state-city dropdown-in-PHP-country-table-state-table

City Table

Then finally you need to have a city table contains the number of cities with an id of states accordingly.

How-to-make country-state-city dropdown-in-PHP-country-table-city-table

What is Logic ??

First I will fetch all the countries from the country table and display them to the first select dropdown, Rest two select dropdowns are empty.

Now I will call the onchange function of javaScript and make an AJAX request by taking the country id.
Then based on the country id, I will query the database and select the number of states which have this country id corresponding to the rows of the state table.

Now states dropdown has come. It is time to get cities based on state selection. Again I will call the function on the selection of state and make an AJAX request by taking the state id and query to the database as above.

Don’t worry I will give this data of SQL files like country, state, city table

Let’s see the folder structure.

How-to-make country-state-city dropdown-in-PHP-country-folder-structure

Step by step process

  • First I will create an index.php file which is our mail file. I will create 3 select dropdowns in HTML of country, state, and city.
  • index.php file has the form tag with the action of script.php. Script.php is to simply print after submitting button.
  • Now I will create an ajax.php file, which is the logic file that receives the id of states and country depending upon AJAX request.
  • config.php is the connection file to the database.
  • Common.php is the PHP class file, which is responsible to query to the database.

Now its time to create these files. Let’s do it.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload Excel(CSV) file with PHP - CodingBirdsOnline.com</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <style>
    input[type=text], select {
        width: 100%;
        padding: 12px 20px;
        margin: 8px 0;
        display: inline-block;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
    }
    input[type=submit] {
        width: 100%;
        background-color: #4CAF50;
        color: white;
        padding: 10px;
        margin: 8px 0;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    input[type=submit]:hover {
        background-color: #45a049;
    }

    #box {
        border-radius: 5px;
        background-color: #f2f2f2;
        padding: 20px;
        margin: 0px 200px 0px 200px;
    }
</style>
</head>
<body>
<div class="jumbotron text-center">
    <h1>Get City by State by Country</h1>
    <p>https://codingbirdsonline.com</p>
</div>
<div id="box">
    <form action="script.php" method="post">
        <?php
        include "config.php";
        include_once "Common.php";
        $common = new Common();
        $countries = $common->getCountry($connection);
        ?>
        <label>Country <span style="color:red">*</span></label>
        <select name="country" id="countryId" class="form-control" onchange="getStateByCountry();">
            <option value="">Country</option>
            <?php
            if ($countries->num_rows > 0 ){
                while ($country = $countries->fetch_object()) {
                    $countryName = $country->name; ?>
                    <option value="<?php echo $country->id; ?>"><?php echo $countryName;?></option>
                <?php }
            }
            ?>
        </select>
        <label>State <span style="color:red">*</span></label>
        <select class="form-control" name="state" id="stateId" onchange="getCityByState();" >
            <option value="">State</option>
        </select>

        <label>City <span style="color:red">*</span></label>
        <select class="form-control" name="city" id="cityDiv">
            <option value="">City</option>
        </select>

        <input type="submit" value="Submit">
    </form>
</div>
<script>
    function getStateByCountry() {
        var countryId = $("#countryId").val();
        $.post("ajax.php",{getStateByCountry:'getStateByCountry',countryId:countryId},function (response) {
            var data = response.split('^');
            $("#stateId").html(data[1]);
        });
    }
    function getCityByState() {
        var stateId = $("#stateId").val();
        $.post("ajax.php",{getCityByState:'getCityByState',stateId:stateId},function (response) {
            var data = response.split('^');
            $("#cityDiv").html(data[1]);
        });
    }
</script>
</body>
</html>

ajax.php

<?php
include "config.php";
include_once "Common.php";
if (isset($_POST['getStateByCountry']) == "getStateByCountry") {
    $countryId = $_POST['countryId'];
    $common = new Common();
    $states = $common->getStateByCountry($connection,$countryId);
    $stateData = '<option value="">State</option>';
    if ($states->num_rows>0){
        while ($state = $states->fetch_object()) {
            $stateData .= '<option value="'.$state->id.'">'.$state->statename.'</option>';
        }
    }
    echo "test^".$stateData;
}
if (isset($_POST['getCityByState']) == "getCityByState") {
    $stateId = $_POST['stateId'];
    $common = new Common();
    $cities = $common->getCityByState($connection,$stateId);
    $cityData = '<option value="">City</option>';
    if ($cities->num_rows>0){
        while ($city = $cities->fetch_object()) {
            $cityData .= '<option value="'.$city->id.'">'.$city->cityName.'</option>';
        }
    }
    echo "test^".$cityData;
}

Common.php

<?php
/**
 * Created by PhpStorm.
 * User: Ankit
 * Date: 11/29/2018
 * Time: 7:50 PM
 */

class Common
{
  public function getCountry($connection)
  {
      $mainQuery = "SELECT * FROM bird_countries";
      $result1 = $connection->query($mainQuery) or die("Error in main Query".$connection->error);
      return $result1;
  }

  public function getStateByCountry($connection,$countryId){
      $query = "SELECT * FROM bird_states WHERE countryId='$countryId'";
      $result = $connection->query($query) or die("Error in  Query".$connection->error);
      return $result;
  }

  public function getCityByState($connection,$stateId){
      $query = "SELECT * FROM bird_cities WHERE state_id='$stateId'";
      $result = $connection->query($query) or die("Error in  Query".$connection->error);
      return $result;
  }
}

script.php

<?php
if (isset($_POST['submit'])) {
    $country = $_POST['country'];
    $state = $_POST['state'];
    $city = $_POST['city'];

    echo 'Country is: '. $country; echo '<br/>';
    echo 'State is  : '. $state; echo '<br/>';
    echo 'City is   : '. $city; echo '<br/>';
}

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Now after creating these files to your editor, importing tables which I will provide and making a connection to your database with config.php file, Its time to test it. When you run it you will get output like below.

How-to-make country-state-city dropdown-in-PHP-output

Now as you see out in the browser, if you select a country, the states will appear according to that country. If you select the state then city as simple as that. You can also put a loader indicator while data is loading on the selected country. Learn how to create loading spinner indicator in jQuery ajax.

Source Code & Demo

So you enjoyed this tutorial and learned how to code this in easy ways. If you have any problem you can download the full working source code here. Check this demo.

Conclusion

In this tutorial, you learned about how to make country-state-city dependent dropdown or cascading dropdown. I hope you have enjoyed this tutorial. If there is anything for improvement, let me know I will be happy. If you face any problem with doing this, you can comment I will help.

If you want to learn how to upload excel(CSV) file to a database with PHP & MySQL in an easy way then you are in the right place. Also, read this how to Upload Multiple Images

Welcome to this blog, my name is Ankit and today I will tell how to do this. Saving an entry of data one by one to the database is the most difficult task in software or web application. Check this demo.

Why we need it?
Generally, We save data via FORM contains some fields like name, email, contact, gender or anything else. 

But imagine if there are hundreds or thousands of records of person or students, then manually saving the data is much complicated. But don’t worry we have something very interesting in PHP.
Then Solution?

The solution to this problem is that, If you can combine that data in an excel sheet or CSV format, then we can write a code in such a way that every entry is in an excel sheet will be saved to a database.
Now that’s enough to understand. Let’s dive into code.

The process of how to upload excel(CSV)

  • Create index.php. This will be a form to upload
  • Create excel-script.php. This is the logic of the code
  • Create a config.php. This is the connection file to the database
  • Create a Common.php. This is class has the function to upload in the database
  • Create a table named bird_excel_users.sql to the database that will save the data of the file

Now let’s create these files.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload Excel(CSV) file with PHP - CodingBirdsOnline.com</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
</head>
<body>
<div class="jumbotron text-center">
    <h1>Upload Excel(CSV) file with PHP</h1>
    <p>https://codingbirdsonline.com</p>
</div>
<div class="container">
    <form action="excel-script.php" method="post" enctype="multipart/form-data">
       <div class="row">
           <div class="col-md-4">
               <div class="form-group">
                   <input type="file" name="excelDoc" id="excelDoc" class="form-control" />
               </div>
           </div>
           <div class="col-md-4">
               <input type="submit" name="uploadBtn" id="uploadBtn" value="Upload Excel" class="btn btn-success" />
           </div>
       </div>
    </form>
</div>
</body>
</html>

This index.php file has form action uses excel-script.php.

excel-script.php

<?php
include  "config.php";
include_once  "Common.php";

if($_FILES['excelDoc']['name']) {
    $arrFileName = explode('.', $_FILES['excelDoc']['name']);
    if ($arrFileName[1] == 'csv') {
        $handle = fopen($_FILES['excelDoc']['tmp_name'], "r");
        $count = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $count++;
            if ($count == 1) {
                continue; // skip the heading header of sheet
            }
                $name = $connection->real_escape_string($data[0]);
                $mobile = $connection->real_escape_string($data[1]);
                $email = $connection->real_escape_string($data[2]);
                $common = new Common();
                $SheetUpload = $common->uploadData($connection,$name,$mobile,$email);
        }
        if ($SheetUpload){
            echo "<script>alert('Excel file has been uploaded successfully !');window.location.href='index.php';</script>";
        }
    }
}

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Common.php

<?php
/**
 * Created by PhpStorm.
 * User: kc
 * Date: 11/29/2018
 * Time: 7:50 PM
 */

class Common
{
  public function uploadData($connection,$name,$contact,$email)
  {
      $mainQuery = "INSERT INTO  bird_excel_users SET name='$name',contact='$contact',email='$email'";
      $result1 = $connection->query($mainQuery) or die("Error in main Query".$connection->error);
      return $result1;
  }
}

bird_excel_users.sql

ATTACHMENT DETAILS how-to-upload-excelCSV-file-to-a-database-with-PHP-MySQL-table-coding-birds-online.png

If you face any errors in coding, then you can comment and I will surely help. And you can download the source code from here.

If you still face any problem, you can watch my video also.

Sending email is mostly used in a variety of websites and web applications. It mostly happens when you send an email by PHP code copied from other websites or blog, it goes to the spam folder. If you want to resolve this issue then you are in the right place. You can check the demo.

Hi, there I am Ankit will tell you how to code so that your email will not go to the spam folder.
Sending email messages is very common things for a web application, for example, sending a welcome email when a user creates an account on your website, sending newsletters to your registered users, or getting user feedback or comment through the website’s contact form, and so on.
 
For doing this, PHP provides a built-in PHP function called mail( ) for creating and sending email messages to one or more recipients dynamically from your PHP application either in a plain-text form or formatted HTML. The basic syntax of this function can be given with:
 
mail(tosubjectmessageheadersparameters)

This functions 4 required parameters

  • to – This is the first parameter required. Put the email id of the person to which you want to send the emails.
  • subject – This is the 2nd parameter tells the subject of the mail you want, you can write it.
  • message – This is the 3rd parameter. As the name suggests, This is the message what you want to send to recipients.
  • headers – This is the 4th parameter which tells about who is sending the email, what is the name of the sender …etc.
So that’s enough. Let’s make our hands dirty with code.
 
Create the index.php file
 
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js"></script>
    <script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <title>Send Email Example</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <h5 class="card-title text-center">Send Email</h5>
                    <form action="email-script.php" method="post" class="form-signin">
                        <div class="form-label-group">
                            <label for="inputEmail">From <span style="color: #FF0000">*</span></label>
                            <input type="text" name="fromEmail" id="fromEmail" class="form-control"  value="info@codingbirdsonline.com" readonly required autofocus>
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">To <span style="color: #FF0000">*</span></label>
                            <input type="text" name="toEmail" id="toEmail" class="form-control" placeholder="Email address" required autofocus>
                        </div> <br/>
                        <label for="inputPassword">Subject <span style="color: #FF0000">*</span></label>
                        <div class="form-label-group">
                            <input type="text" id="subject" name="subject" class="form-control" placeholder="Subject" required>
                        </div><br/>
                        <label for="inputPassword">Message <span style="color: #FF0000">*</span></label>
                        <div class="form-label-group">
                            <textarea  id="message" name="message" class="form-control" placeholder="Message" required ></textarea>
                        </div> <br/>
                        <button type="submit" name="sendMailBtn" class="btn btn-lg btn-primary btn-block text-uppercase" >Send Email</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

When you will check, you will get this output

 How to send email in PHP step by step-output

In index.php you have <form> tag has the action of email-script.php. This is code for same.

email-script.php

<?php
if (isset($_POST['sendMailBtn'])) {
    $fromEmail = $_POST['fromEmail'];
    $toEmail = $_POST['toEmail'];
    $subjectName = $_POST['subject'];
    $message = $_POST['message'];

    $to = $toEmail;
    $subject = $subjectName;
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= 'From: '.$fromEmail.'<'.$fromEmail.'>' . "\r\n".'Reply-To: '.$fromEmail."\r\n" . 'X-Mailer: PHP/' . phpversion();
    $message = '<!doctype html>
			<html lang="en">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport"
					  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
				<meta http-equiv="X-UA-Compatible" content="ie=edge">
				<title>Document</title>
			</head>
			<body>
			<span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">'.$message.'</span>
				<div class="container">
                 '.$message.'<br/>
                    Regards<br/>
                  '.$fromEmail.'
				</div>
			</body>
			</html>';
    $result = @mail($to, $subject, $message, $headers);

    echo '<script>alert("Email sent successfully !")</script>';
    echo '<script>window.location.href="index.php";</script>';
}

Testing

Now upload to these files to your live server and fill the form, hit the submit button.

How-to-send-email-in-PHP-step-by-step-output-2
How to send email in PHP step by step-output

You just need to copy and paste the code nothing else. The code is very simple. And if you still face any problem you can download the source code from here.

You can also watch this video explained the same as in the above post.

Happy coding 🙂