Sử dụng database + php (ok)

Example 1:

<?php 
	$conexion=mysqli_connect('localhost','root','','prueba');
	$sql="SELECT id,nombre from t_paises";
	$result=mysqli_query($conexion,$sql);
?>
<!DOCTYPE html>
<html>
<head>
  <title>Tutorial</title>
  <link rel="stylesheet" type="text/css" href="select2/select2.min.css">
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="select2/select2.min.js"></script>
</head>
<body>
  <section style="text-align: center;">
    <select id="controlBuscador" style="width: 50%">
      <?php while ($ver=mysqli_fetch_row($result)) {?>
      <option value="<?php echo $ver[0] ?>">
        <?php echo $ver[1] ?>
      </option>
      <?php  } ?>
    </select>
  </section>
</body>

</html>
<script type="text/javascript">
$(document).ready(function() {
  $('#controlBuscador').select2();
});
</script>

Example 2:

index.php

<!DOCTYPE html>
<html>

<head>
  <title>Tutorial selectDB remote ajax using jquery,php and mysql by seegatesite.com</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
  <div>
    <select class="select2"></select>
  </div>
  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  <script type="text/javascript">
  $(".select2").select2({
    placeholder: "Search country here...",
    width: '175px',
    ajax: {
      url: "ajax.php",
      dataType: 'json',
      delay: 250,
      data: function(params) {
        return {
          q: params.term,
          page: params.page
        };
      },
      processResults: function(data, params) {
        params.page = params.page || 1;
        return {
          results: data.items,
          pagination: {
            more: (params.page * 3) < data.total_count
          }
        };
      },
      cache: false
    },
    minimumInputLength: 1,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
  });
  function formatRepo(repo) {
    if(repo.loading) return repo.text;
    return repo.desc;
  }
  function formatRepoSelection(repo) {
    return repo.desc || repo.text;
  }
  </script>
</body>

</html>

dbconn.php

<?php
$dbuserx = 'root';
$dbpassx = '';
class dbconn {
  public $dblocal;
  public function __construct() {}
  public function initDBO() {
    global $dbuserx, $dbpassx;
    try {
      $this->dblocal = new PDO("mysql:host=localhost;dbname=selectdb;charset=latin1", $dbuserx, $dbpassx, [PDO::ATTR_PERSISTENT => true]);
      $this->dblocal->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
      die("Tidak dapat konek ke database");
    }
  }
}
?>

sql.php

<?php
class sql extends dbconn {
  public function __construct() {
    $this->initDBO();
  }
  public function getAllCountry($term) {
    $term = '%' . $term . '%';
    $db   = $this->dblocal;
    try
    {
      $stmt = $db->prepare("SELECT a.* FROM country a WHERE a.country_name LIKE :term OR  a.country_code LIKE :term ");

      $stmt->bindParam("term", $term);
      $stmt->execute();
      $stat[0] = true;
      $stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
      return $stat;
    } catch (PDOException $ex) {
      $stat[0] = false;
      $stat[1] = $ex->getMessage();
      return $stat;
    }
  }
}

ajax.php

<?php
header('Content-Type: application/json');
require_once "dbconn.php";
require_once "sql.php";
$term        = trim(strip_tags($_GET['q']));
$sql         = new sql();
$countrylist = $sql->getAllCountry($term);
$country     = [];
$i           = 0;
foreach ($countrylist[1] as $key) {
  $countrylist[1][$i]['desc'] = $key['country_code'] . ' - ' . $key['country_name'];
  $countrylist[1][$i]['id']   = $key['country_code'];
  $i++;
}
$country['items'] = $countrylist[1];
echo json_encode($country);
?>

Example 3:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Select2 Ajax Example PHP Demo - Kvcodes </title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <meta name="theme-color" content="#343D46">
  <meta name="msapplication-navbutton-color" content="#343D46">
  <meta name="apple-mobile-web-app-status-bar-style" content="#343D46">
  <!--- SEO Things Added by Varadha -->
  <meta content='True' name='HandheldFriendly' />
  <meta content='global' name='distribution' />
  <meta content='all' name='audience' />
  <meta content='general' name='rating' />
  <meta content='all' name='robots' />
  <meta content='en-us' name='language' />
  <meta content='USA' name='country' />
  <meta content='320' name='MobileOptimized' />
  <meta content='Varadharaj V' name='author' />
  <meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible' />
  <meta content='width=device-width, initial-scale=1' name='viewport' />
  <meta content='Copyright (c) 2013 - <?php echo date("Y");?>' Kvcodes' name='dcterms.dateCopyrighted' />
  <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  <link href='http://feeds.feedburner.com/KvCodes' rel='alternate' title='Kvcodes - A Place for Web Tutorials' type='application/rss+xml' />
  <link href='http://www.kvcodes.com' rel='shortlink' />
  <meta name="keywords" content="demo codes, kvcodes demo, demoing articles, articles demo, Kvcodes Projects Demo" />
  <link rel="canonical" href="http://demo.kvcodes.com/" />
  <meta property="og:locale" content="en_US" />
  <meta property="og:type" content="article" />
  <meta property="og:title" content="Select2 Ajax Example PHP Demo" />
  <meta property="og:description" content="The select2 js is widely used to shortlist and filter the select options. When it goes more than 100 in select option. Its hard to navigate and find the right one." />
  <meta property="og:url" content="http://www.kvcodes.com/2016/11/simple-popup-div-using-jquery/" />
  <meta property="og:site_name" content="Kvcodes" />
  <meta property="article:publisher" content="https://www.facebook.com/kvcodes?ref=hl" />
  <meta property="article:author" content="https://www.facebook.com/kvvaradha" />
  <meta property="article:tag" content="Kvcodes Demo" />
  <meta property="article:tag" content="Projects" />
  <meta property="article:tag" content="Demo" />
  <meta property="article:tag" content="Select2" />
  <meta property="article:section" content="jQuery" />
  <meta property="article:published_time" content="2014-02-11T17:21:45+00:00" />
  <meta property="article:modified_time" content="2016-10-20T11:09:52+00:00" />
  <meta property="og:updated_time" content="2016-10-20T11:09:52+00:00" />
  <meta property="og:image:width" content="1135" />
  <meta property="og:image:height" content="754" />
  <style>
  /* Reset */
  html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    font-family: 'PT Sans';
    vertical-align: baseline;
  }
  article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
    display: block;
  }
  body {
    line-height: 1;
  }
  ol, ul {
    list-style: none;
  }
  blockquote, q {
    quotes: none;
  }
  blockquote:before, blockquote:after, q:before, q:after {
    content: '';
    content: none;
  }
  h3 {
    color: #fff;
    font-size: 20px;
  }
  table {
    border-collapse: collapse;
    border-spacing: 0;
  }
  body {
    -webkit-text-size-adjust: none;
    background: #203748;
  }
  html, body, #header, #main {
    height: 100%;
  }
  * {
    margin: 0;
    padding: 0;
  }
  a {
    text-decoration: none;
  }
  #footer a {
    color: #03A9F4;
  }
  #footer a:hover {
    color: #39d084;
  }
  #wrap {
    min-height: 100%;
  }
  #main {
    overflow: auto;
    padding-bottom: 60px;
    /* must be same height as the footer */
  }
  #footer {
    position: relative;
    margin-top: -60px;
    /* negative value of footer height */
    height: 180px;
    clear: both;
    color: #fff;
  }
  #header {
    background: #39d084;
    height: 30px;
    color: #fff;
    padding: 1%;
  }
  #header a {
    color: #fff;
  }
  #header .logo {
    width: 100%;
    text-align: center;
    float: left;
  }
  #header .logo a {
    font-size: 24px;
  }
  #header ul {
    list-style: none;
    float: right;
  }
  #header ul li {
    float: left;
    margin: 0 8px;
  }
  .header-wrap {
    margin: 0 auto;
    width: 800px;
  }
  a {
    cursor: pointer;
  }
  .content {
    padding: 8px;
    line-height: 25px;
    font-size: 16px;
    margin: 0 auto;
    width: 800px;
  }
  #footer {
    height: 20px;
    padding: 20px;
    background: #355267;
  }
  h1 {
    font-size: 20px;
    font-weight: 600;
    text-align: center;
    margin-top: 2%;
    color: #16b4fb;
  }
  p {
    color: #d4d3d3;
  }
  .select2 {
    background: #fff;
  }
  span#kv_form_close:hover {
    color: #e0190b;
  }
  @media screen and (max-width: 440px) {
    #sub_div_form {
      width: 290px;
      padding: 35px;
    }
  }
  </style>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://www.kvcodes.com/theme/js/jquery.min.js"> </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  <script>
  $(document).ready(function() {
    // Static dropd down 
    $(".static").select2();
    //Ajax array example
    $('.itemName').select2({
      placeholder: 'Select an item',
      theme: "material",
      allowClear: true,
      ajax: {
        url: 'ajax.php?filter=yes',
        dataType: 'json',
        delay: 250,
        processResults: function(data) {
          return {
            results: data
          };
        },
        cache: true
      }
    });
    // Filter from database
    $('.FilterDB').select2({
      placeholder: 'Select an item',
      theme: "material",
      allowClear: true,
      ajax: {
        url: 'ajax.php?filterDB=yes',
        dataType: 'json',
        delay: 250,
        data: function(params) {
        return {
          q: params.term
        	};
      	},
        processResults: function(data) {
          return {
            results: data
          };
        },
        cache: true
      }
    });
  });
  </script>
</head>

<body>
  <div id="wrap">
    <div id="header">
      <!-- Header -->
      <div class="header-wrap">
        <div class="logo">
          <a href="https://www.kvcodes.com/2019/04/select2-ajax-example-php/"> <img src="https://www.kvcodes.com/theme/images/kv_logo.png" alt="Home" style="    height: 50px; margin-top: -10px; vertical-align: middle;"> - Demo</a>
        </div>
        <!-- Nav -->
        <nav id="main-menu" class="main_nav"></nav>
      </div>
    </div>
    <div id="main" class="content">
      <h1>Welcome to Demo Page </h1><br />
      <p> Static Example </p>
      <select class="static form-control" style="width:500px" name="itemName">
        <option value="0"> None </option>
        <option value="1"> One </option>
        <option value="2"> Two </option>
        <option value="3"> Three </option>
        <option value="4"> Four </option>
        <option value="5"> Five </option>
        <option value="6"> Six </option>
        <option value="7"> Seven </option>
      </select>
      <br><br>
      <p> Ajax PHP from array </p>
      <select class="itemName form-control" style="width:500px" name="itemName"></select>
      <br>
      <p> Select2 Search from database table</p>
      <select class="FilterDB form-control" style="width:500px" name="FilterDB"></select>
    </div>
  </div>
</body>

</html>
<?php 


$array = array(
  array('id' => '1','iso' => 'AD','local_name' => 'Andorra'),
  array('id' => '2','iso' => 'AE','local_name' => 'United Arab Emirates'),
  array('id' => '3','iso' => 'AF','local_name' => 'Afghanistan'),
  array('id' => '4','iso' => 'AG','local_name' => 'Antigua and Barbuda'),
  array('id' => '5','iso' => 'AI','local_name' => 'Anguilla'),
  array('id' => '6','iso' => 'AL','local_name' => 'Albania'),
  array('id' => '7','iso' => 'AM','local_name' => 'Armenia'),
  array('id' => '8','iso' => 'AN','local_name' => 'Netherlands Antilles'),
  array('id' => '9','iso' => 'AO','local_name' => 'Angola'),
  array('id' => '10','iso' => 'AQ','local_name' => 'Antarctica'),
  array('id' => '11','iso' => 'AR','local_name' => 'Argentina'),
  array('id' => '12','iso' => 'AS','local_name' => 'American Samoa'),
  array('id' => '13','iso' => 'AT','local_name' => 'Austria'),
  array('id' => '14','iso' => 'AU','local_name' => 'Australia'),
  array('id' => '15','iso' => 'AW','local_name' => 'Aruba'),
  array('id' => '16','iso' => 'AX','local_name' => 'Aland Islands'),
  array('id' => '17','iso' => 'AZ','local_name' => 'Azerbaijan'),
  array('id' => '18','iso' => 'BA','local_name' => 'Bosnia and Herzegovina'),
  array('id' => '19','iso' => 'BB','local_name' => 'Barbados'),
  array('id' => '20','iso' => 'BD','local_name' => 'Bangladesh'),
  array('id' => '21','iso' => 'BE','local_name' => 'Belgium'),
  array('id' => '22','iso' => 'BF','local_name' => 'Burkina Faso'),
  array('id' => '23','iso' => 'BG','local_name' => 'Bulgaria'),
  array('id' => '24','iso' => 'BH','local_name' => 'Bahrain'),
  array('id' => '25','iso' => 'BI','local_name' => 'Burundi'),
  array('id' => '26','iso' => 'BJ','local_name' => 'Benin'),
  array('id' => '27','iso' => 'BL','local_name' => 'Saint Barthlemy'),
  array('id' => '28','iso' => 'BM','local_name' => 'Bermuda'),
  array('id' => '29','iso' => 'BN','local_name' => 'Brunei Darussalam'),
  array('id' => '30','iso' => 'BO','local_name' => 'BoliviaBolivia, Plurinational state of'),
  array('id' => '31','iso' => 'BR','local_name' => 'Brazil'),
  array('id' => '32','iso' => 'BS','local_name' => 'Bahamas'),
  array('id' => '33','iso' => 'BT','local_name' => 'Bhutan'),
  array('id' => '34','iso' => 'BV','local_name' => 'Bouvet Island'),
  array('id' => '35','iso' => 'BW','local_name' => 'Botswana'),
  array('id' => '36','iso' => 'BY','local_name' => 'Belarus'),
  array('id' => '37','iso' => 'BZ','local_name' => 'Belize'),
  array('id' => '38','iso' => 'CA','local_name' => 'Canada'),
  array('id' => '39','iso' => 'CC','local_name' => 'Cocos (Keeling) Islands'),
  array('id' => '40','iso' => 'CD','local_name' => 'Congo, The Democratic Republic of the'),
  array('id' => '41','iso' => 'CF','local_name' => 'Central African Republic'),
  array('id' => '42','iso' => 'CG','local_name' => 'Congo'),
  array('id' => '43','iso' => 'CH','local_name' => 'Switzerland'),
  array('id' => '45','iso' => 'CK','local_name' => 'Cook Islands'),
  array('id' => '46','iso' => 'CL','local_name' => 'Chile'),
  array('id' => '47','iso' => 'CM','local_name' => 'Cameroon'),
  array('id' => '48','iso' => 'CN','local_name' => 'China'),
  array('id' => '49','iso' => 'CO','local_name' => 'Colombia'),
  array('id' => '50','iso' => 'CR','local_name' => 'Costa Rica'),
  array('id' => '51','iso' => 'CU','local_name' => 'Cuba'),
  array('id' => '52','iso' => 'CV','local_name' => 'Cape Verde'),
  array('id' => '53','iso' => 'CX','local_name' => 'Christmas Island'),
  array('id' => '54','iso' => 'CY','local_name' => 'Cyprus'),
  array('id' => '55','iso' => 'CZ','local_name' => 'Czech Republic'),
  array('id' => '56','iso' => 'DE','local_name' => 'Germany'),
  array('id' => '57','iso' => 'DJ','local_name' => 'Djibouti'),
  array('id' => '58','iso' => 'DK','local_name' => 'Denmark'),
  array('id' => '59','iso' => 'DM','local_name' => 'Dominica'),
  array('id' => '60','iso' => 'DO','local_name' => 'Dominican Republic'),
  array('id' => '61','iso' => 'DZ','local_name' => 'Algeria'),
  array('id' => '62','iso' => 'EC','local_name' => 'Ecuador'),
  array('id' => '63','iso' => 'EE','local_name' => 'Estonia'),
  array('id' => '64','iso' => 'EG','local_name' => 'Egypt'),
  array('id' => '65','iso' => 'EH','local_name' => 'Western Sahara'),
  array('id' => '66','iso' => 'ER','local_name' => 'Eritrea'),
  array('id' => '67','iso' => 'ES','local_name' => 'Spain'),
  array('id' => '68','iso' => 'ET','local_name' => 'Ethiopia'),
  array('id' => '69','iso' => 'FI','local_name' => 'Finland'),
  array('id' => '70','iso' => 'FJ','local_name' => 'Fiji'),
  array('id' => '71','iso' => 'FK','local_name' => 'Falkland Islands (Malvinas)'),
  array('id' => '72','iso' => 'FM','local_name' => 'Micronesia, Federated States of'),
  array('id' => '73','iso' => 'FO','local_name' => 'Faroe Islands'),
  array('id' => '74','iso' => 'FR','local_name' => 'France'),
  array('id' => '75','iso' => 'GA','local_name' => 'Gabon'),
  array('id' => '76','iso' => 'GB','local_name' => 'United Kingdom'),
  array('id' => '77','iso' => 'GD','local_name' => 'Grenada'),
  array('id' => '78','iso' => 'GE','local_name' => 'Georgia'),
  array('id' => '79','iso' => 'GF','local_name' => 'French Guiana'),
  array('id' => '80','iso' => 'GG','local_name' => 'Guernsey'),
  array('id' => '81','iso' => 'GH','local_name' => 'Ghana'),
  array('id' => '82','iso' => 'GI','local_name' => 'Gibraltar'),
  array('id' => '83','iso' => 'GL','local_name' => 'Greenland'),
  array('id' => '84','iso' => 'GM','local_name' => 'Gambia'),
  array('id' => '85','iso' => 'GN','local_name' => 'Guinea'),
  array('id' => '86','iso' => 'GP','local_name' => 'Guadeloupe'),
  array('id' => '87','iso' => 'GQ','local_name' => 'Equatorial Guinea'),
  array('id' => '88','iso' => 'GR','local_name' => 'Greece'),
  array('id' => '89','iso' => 'GS','local_name' => 'South Georgia and the South Sandwich Islands'),
  array('id' => '90','iso' => 'GT','local_name' => 'Guatemala'),
  array('id' => '91','iso' => 'GU','local_name' => 'Guam'),
  array('id' => '92','iso' => 'GW','local_name' => 'Guinea-Bissau'),
  array('id' => '93','iso' => 'GY','local_name' => 'Guyana'),
  array('id' => '94','iso' => 'HK','local_name' => 'Hong Kong'),
  array('id' => '95','iso' => 'HM','local_name' => 'Heard Island and McDonald Islands'),
  array('id' => '96','iso' => 'HN','local_name' => 'Honduras'),
  array('id' => '97','iso' => 'HR','local_name' => 'Croatia'),
  array('id' => '98','iso' => 'HT','local_name' => 'Haiti'),
  array('id' => '99','iso' => 'HU','local_name' => 'Hungary'),
  array('id' => '100','iso' => 'ID','local_name' => 'Indonesia'),
  array('id' => '101','iso' => 'IE','local_name' => 'Ireland'),
  array('id' => '102','iso' => 'IL','local_name' => 'Israel'),
  array('id' => '103','iso' => 'IM','local_name' => 'Isle of Man'),
  array('id' => '104','iso' => 'IN','local_name' => 'India'),
  array('id' => '105','iso' => 'IO','local_name' => 'British Indian Ocean Territory'),
  array('id' => '106','iso' => 'IQ','local_name' => 'Iraq'),
  array('id' => '107','iso' => 'IR','local_name' => 'Iran, Islamic Republic of'),
  array('id' => '108','iso' => 'IS','local_name' => 'Iceland'),
  array('id' => '109','iso' => 'IT','local_name' => 'Italy'),
  array('id' => '110','iso' => 'JE','local_name' => 'Jersey'),
  array('id' => '111','iso' => 'JM','local_name' => 'Jamaica'),
  array('id' => '112','iso' => 'JO','local_name' => 'Jordan'),
  array('id' => '113','iso' => 'JP','local_name' => 'Japan'),
  array('id' => '114','iso' => 'KE','local_name' => 'Kenya'),
  array('id' => '115','iso' => 'KG','local_name' => 'Kyrgyzstan'),
  array('id' => '116','iso' => 'KH','local_name' => 'Cambodia'),
  array('id' => '117','iso' => 'KI','local_name' => 'Kiribati'),
  array('id' => '118','iso' => 'KM','local_name' => 'Comoros'),
  array('id' => '119','iso' => 'KN','local_name' => 'Saint Kitts and Nevis'),
  array('id' => '120','iso' => 'KP','local_name' => 'Korea, Democratic People&#39;s Republic of'),
  array('id' => '121','iso' => 'KR','local_name' => 'Korea, Republic of'),
  array('id' => '122','iso' => 'KW','local_name' => 'Kuwait'),
  array('id' => '123','iso' => 'KY','local_name' => 'Cayman Islands'),
  array('id' => '124','iso' => 'KZ','local_name' => 'Kazakhstan'),
  array('id' => '125','iso' => 'LA','local_name' => 'Lao People&#39;s Democratic Republic'),
  array('id' => '126','iso' => 'LB','local_name' => 'Lebanon'),
  array('id' => '127','iso' => 'LC','local_name' => 'Saint Lucia'),
  array('id' => '128','iso' => 'LI','local_name' => 'Liechtenstein'),
  array('id' => '129','iso' => 'LK','local_name' => 'Sri Lanka'),
  array('id' => '130','iso' => 'LR','local_name' => 'Liberia'),
  array('id' => '131','iso' => 'LS','local_name' => 'Lesotho'),
  array('id' => '132','iso' => 'LT','local_name' => 'Lithuania'),
  array('id' => '133','iso' => 'LU','local_name' => 'Luxembourg'),
  array('id' => '134','iso' => 'LV','local_name' => 'Latvia'),
  array('id' => '135','iso' => 'LY','local_name' => 'Libyan Arab Jamahiriya'),
  array('id' => '136','iso' => 'MA','local_name' => 'Morocco'),
  array('id' => '137','iso' => 'MC','local_name' => 'Monaco'),
  array('id' => '138','iso' => 'MD','local_name' => 'Moldova, Republic of'),
  array('id' => '139','iso' => 'ME','local_name' => 'Montenegro'),
  array('id' => '140','iso' => 'MF','local_name' => 'Saint Martin'),
  array('id' => '141','iso' => 'MG','local_name' => 'Madagascar'),
  array('id' => '142','iso' => 'MH','local_name' => 'Marshall Islands'),
  array('id' => '143','iso' => 'MK','local_name' => 'Macedonia'),
  array('id' => '144','iso' => 'ML','local_name' => 'Mali'),
  array('id' => '145','iso' => 'MM','local_name' => 'Myanmar'),
  array('id' => '146','iso' => 'MN','local_name' => 'Mongolia'),
  array('id' => '147','iso' => 'MO','local_name' => 'Macao'),
  array('id' => '148','iso' => 'MP','local_name' => 'Northern Mariana Islands'),
  array('id' => '149','iso' => 'MQ','local_name' => 'Martinique'),
  array('id' => '150','iso' => 'MR','local_name' => 'Mauritania'),
  array('id' => '151','iso' => 'MS','local_name' => 'Montserrat'),
  array('id' => '152','iso' => 'MT','local_name' => 'Malta'),
  array('id' => '153','iso' => 'MU','local_name' => 'Mauritius'),
  array('id' => '154','iso' => 'MV','local_name' => 'Maldives'),
  array('id' => '155','iso' => 'MW','local_name' => 'Malawi'),
  array('id' => '156','iso' => 'MX','local_name' => 'Mexico'),
  array('id' => '157','iso' => 'MY','local_name' => 'Malaysia'),
  array('id' => '158','iso' => 'MZ','local_name' => 'Mozambique'),
  array('id' => '159','iso' => 'NA','local_name' => 'Namibia'),
  array('id' => '160','iso' => 'NC','local_name' => 'New Caledonia'),
  array('id' => '161','iso' => 'NE','local_name' => 'Niger'),
  array('id' => '162','iso' => 'NF','local_name' => 'Norfolk Island'),
  array('id' => '163','iso' => 'NG','local_name' => 'Nigeria'),
  array('id' => '164','iso' => 'NI','local_name' => 'Nicaragua'),
  array('id' => '165','iso' => 'NL','local_name' => 'Netherlands'),
  array('id' => '166','iso' => 'NO','local_name' => 'Norway'),
  array('id' => '167','iso' => 'NP','local_name' => 'Nepal'),
  array('id' => '168','iso' => 'NR','local_name' => 'Nauru'),
  array('id' => '169','iso' => 'NU','local_name' => 'Niue'),
  array('id' => '170','iso' => 'NZ','local_name' => 'New Zealand'),
  array('id' => '171','iso' => 'OM','local_name' => 'Oman'),
  array('id' => '172','iso' => 'PA','local_name' => 'Panama'),
  array('id' => '173','iso' => 'PE','local_name' => 'Peru'),
  array('id' => '174','iso' => 'PF','local_name' => 'French Polynesia'),
  array('id' => '175','iso' => 'PG','local_name' => 'Papua New Guinea'),
  array('id' => '176','iso' => 'PH','local_name' => 'Philippines'),
  array('id' => '177','iso' => 'PK','local_name' => 'Pakistan'),
  array('id' => '178','iso' => 'PL','local_name' => 'Poland'),
  array('id' => '179','iso' => 'PM','local_name' => 'Saint Pierre and Miquelon'),
  array('id' => '180','iso' => 'PN','local_name' => 'Pitcairn'),
  array('id' => '181','iso' => 'PR','local_name' => 'Puerto Rico'),
  array('id' => '182','iso' => 'PS','local_name' => 'Palestinian Territory, Occupied'),
  array('id' => '183','iso' => 'PT','local_name' => 'Portugal'),
  array('id' => '184','iso' => 'PW','local_name' => 'Palau'),
  array('id' => '185','iso' => 'PY','local_name' => 'Paraguay'),
  array('id' => '186','iso' => 'QA','local_name' => 'Qatar'),
  array('id' => '188','iso' => 'RO','local_name' => 'Romania'),
  array('id' => '189','iso' => 'RS','local_name' => 'Serbia'),
  array('id' => '190','iso' => 'RU','local_name' => 'Russian Federation'),
  array('id' => '191','iso' => 'RW','local_name' => 'Rwanda'),
  array('id' => '192','iso' => 'SA','local_name' => 'Saudi Arabia'),
  array('id' => '193','iso' => 'SB','local_name' => 'Solomon Islands'),
  array('id' => '194','iso' => 'SC','local_name' => 'Seychelles'),
  array('id' => '195','iso' => 'SD','local_name' => 'Sudan'),
  array('id' => '196','iso' => 'SE','local_name' => 'Sweden'),
  array('id' => '197','iso' => 'SG','local_name' => 'Singapore'),
  array('id' => '198','iso' => 'SH','local_name' => 'Saint Helena'),
  array('id' => '199','iso' => 'SI','local_name' => 'Slovenia'),
  array('id' => '200','iso' => 'SJ','local_name' => 'Svalbard and Jan Mayen'),
  array('id' => '201','iso' => 'SK','local_name' => 'Slovakia'),
  array('id' => '202','iso' => 'SL','local_name' => 'Sierra Leone'),
  array('id' => '203','iso' => 'SM','local_name' => 'San Marino'),
  array('id' => '204','iso' => 'SN','local_name' => 'Senegal'),
  array('id' => '205','iso' => 'SO','local_name' => 'Somalia'),
  array('id' => '206','iso' => 'SR','local_name' => 'Suriname'),
  array('id' => '207','iso' => 'ST','local_name' => 'Sao Tome and Principe'),
  array('id' => '208','iso' => 'SV','local_name' => 'El Salvador'),
  array('id' => '209','iso' => 'SY','local_name' => 'Syrian Arab Republic'),
  array('id' => '210','iso' => 'SZ','local_name' => 'Swaziland'),
  array('id' => '211','iso' => 'TC','local_name' => 'Turks and Caicos Islands'),
  array('id' => '212','iso' => 'TD','local_name' => 'Chad'),
  array('id' => '213','iso' => 'TF','local_name' => 'French Southern Territories'),
  array('id' => '214','iso' => 'TG','local_name' => 'Togo'),
  array('id' => '215','iso' => 'TH','local_name' => 'Thailand'),
  array('id' => '216','iso' => 'TJ','local_name' => 'Tajikistan'),
  array('id' => '217','iso' => 'TK','local_name' => 'Tokelau'),
  array('id' => '218','iso' => 'TL','local_name' => 'Timor-Leste'),
  array('id' => '219','iso' => 'TM','local_name' => 'Turkmenistan'),
  array('id' => '220','iso' => 'TN','local_name' => 'Tunisia'),
  array('id' => '221','iso' => 'TO','local_name' => 'Tonga'),
  array('id' => '222','iso' => 'TR','local_name' => 'Turkey'),
  array('id' => '223','iso' => 'TT','local_name' => 'Trinidad and Tobago'),
  array('id' => '224','iso' => 'TV','local_name' => 'Tuvalu'),
  array('id' => '225','iso' => 'TW','local_name' => 'Taiwan'),
  array('id' => '226','iso' => 'TZ','local_name' => 'Tanzania, United Republic of'),
  array('id' => '227','iso' => 'UA','local_name' => 'Ukraine'),
  array('id' => '228','iso' => 'UG','local_name' => 'Uganda'),
  array('id' => '229','iso' => 'UM','local_name' => 'United States Minor Outlying Islands'),
  array('id' => '230','iso' => 'US','local_name' => 'United States'),
  array('id' => '231','iso' => 'UY','local_name' => 'Uruguay'),
  array('id' => '232','iso' => 'UZ','local_name' => 'Uzbekistan'),
  array('id' => '233','iso' => 'VA','local_name' => 'Holy See (Vatican City State)'),
  array('id' => '234','iso' => 'VC','local_name' => 'Saint Vincent and the Grenadines'),
  array('id' => '235','iso' => 'VE','local_name' => 'Venezuela, Bolivarian Republic of'),
  array('id' => '236','iso' => 'VG','local_name' => 'Virgin Islands, British'),
  array('id' => '237','iso' => 'VI','local_name' => 'Virgin Islands, U.S.'),
  array('id' => '238','iso' => 'VN','local_name' => 'Viet Nam'),
  array('id' => '239','iso' => 'VU','local_name' => 'Vanuatu'),
  array('id' => '240','iso' => 'WF','local_name' => 'Wallis and Futuna'),
  array('id' => '241','iso' => 'WS','local_name' => 'Samoa'),
  array('id' => '242','iso' => 'YE','local_name' => 'Yemen'),
  array('id' => '243','iso' => 'YT','local_name' => 'Mayotte'),
  array('id' => '244','iso' => 'ZA','local_name' => 'South Africa'),
  array('id' => '245','iso' => 'ZM','local_name' => 'Zambia'),
  array('id' => '246','iso' => 'ZW','local_name' => 'Zimbabwe')
);
if(isset($_GET['filter']) && $_GET['filter'] == 'yes') {
  $filter = [];
  foreach($array as $single){
    if(strpos($single['local_name'], $_GET['q']) !== false)
      $filter[] = array('id' => $single['iso'], 'text' => $single['local_name']);
  }
  echo json_encode($filter);
} 
elseif(isset($_GET['filterDB']) && $_GET['filterDB'] == 'yes') {
  define ('DB_USER', "root");
  define ('DB_PASSWORD', "");
  define ('DB_DATABASE', "select2");
  define ('DB_HOST', "localhost");
  $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
  $sql = "SELECT countries.id, countries.local_name FROM countries WHERE local_name LIKE '%".$_GET['q']."%' LIMIT 10";
  $result = $mysqli->query($sql);
  $json = [];
  while($row = $result->fetch_assoc()){
    $json[] = ['id'=>$row['id'], 'text'=>$row['local_name']];
  }
  echo json_encode($json);
};

Example 4:

index.php

<?php
include 'DBController.php';
$db_handle = new DBController();
$countryResult = $db_handle->runQuery("SELECT DISTINCT Country FROM tbl_user ORDER BY Country ASC");
?>
<html>

<head>
  <link href="style.css" type="text/css" rel="stylesheet" />
  <title>Multiselect Dropdown Filter</title>
</head>

<body>
  <h2>Multiselect Dropdown Filter</h2>
  <form method="POST" name="search" action="index.php">
    <div id="demo-grid">
      <div class="search-box">
        <select id="Place" name="country[]" multiple="multiple">
          <option value="0" selected="selected">Select Country</option>
          <?php
            if (! empty($countryResult)) {
              foreach ($countryResult as $key => $value) {
                echo '<option value="' . $countryResult[$key]['Country'] . '">' . $countryResult[$key]['Country'] . '</option>';
              }
            }
          ?>
        </select><br> <br>
        <button id="Filter">Search</button>
      </div>
      <?php
        if (! empty($_POST['country'])) {
      ?>
      <table cellpadding="10" cellspacing="1">
        <thead>
          <tr>
            <th><strong>Name</strong></th>
            <th><strong>Gender</strong></th>
            <th><strong>Country</strong></th>
          </tr>
        </thead>
        <tbody>
          <?php
            $query = "SELECT * from tbl_user";
            $i = 0;
            $selectedOptionCount = count($_POST['country']);
            $selectedOption = "";
            while ($i < $selectedOptionCount) {
              $selectedOption = $selectedOption . "'" . $_POST['country'][$i] . "'";
              if ($i < $selectedOptionCount - 1) {
                  $selectedOption = $selectedOption . ", ";
              }
              $i ++;
            }
            $query = $query . " WHERE country in (" . $selectedOption . ")";
            $result = $db_handle->runQuery($query);
          }
            if (! empty($result)) {
            foreach ($result as $key => $value) {
          ?>
          <tr>
            <td>
              <div class="col" id="user_data_1">
                <?php echo $result[$key]['Name']; ?>
              </div>
            </td>
            <td>
              <div class="col" id="user_data_2">
                <?php echo $result[$key]['Gender']; ?>
              </div>
            </td>
            <td>
              <div class="col" id="user_data_3">
                <?php echo $result[$key]['Country']; ?>
              </div>
            </td>
          </tr>
          <?php
            }
          ?>
        </tbody>
      </table>
      <?php
        }
      ?>
    </div>
  </form>
</body>

</html>

DBController.php

<?php
class DBController {
  private $host     = "localhost";
  private $user     = "root";
  private $password = "";
  private $database = "phpsamples";
  private $conn;
  function __construct() {
    $this->conn = $this->connectDB();
  }
  function connectDB() {
    $conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
    return $conn;
  }
  function runQuery($query) {
    $result = mysqli_query($this->conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
      $resultset[] = $row;
    }
    if (!empty($resultset)) {
      return $resultset;
    }
  }
}
?>

style.css

body {
  width: 610px;
}
#demo-grid {
  margin-bottom: 30px;
}
#demo-grid .txt-heading {
  background-color: #D3F5B8;
}
#demo-grid table {
  width: 100%;
  background-color: #F0F0F0;
}
#demo-grid table th {
  text-align: left;
}
#demo-grid table td {
  background-color: #FFFFFF;
}
.search-box {
  border: 1px solid #F0F0F0;
  background-color: #C8EEFD;
  margin: 10px 0px;
}
button#Filter {
  padding: 5px 30px;
  background: #586e75;
  border: #485c61 1px solid;
  color: #FFF;
  border-radius: 2px;
  cursor: pointer;
  margin-left: 20px;
  margin-bottom: 5px;
}
select#Place {
  margin-left: 20px;
  margin-top: 12px;
  padding-bottom: 25px;
}

Last updated