PHP MySQLi How To Use Select2 for Multiple Select Tutorial

Reading Time: 6 minutes
2,593 Views

Inside this article we will use the concept of PHP MySQLi How To Use Select2 For Multiple Select Tutorial. Article contains classified information about loading data into select2 plugin via ajax request.

How to Load data using jQuery AJAX in Select2 using PHP MySQLi, we will also see in a very clear way here. Multi select means we will have multi options to pick values from select dropdown.

Select2 is a jquery plugin which alters HTML element and create dynamic element with ajax data. Select2 also contains itself a search function into it. This tutorial will cover all easy steps to integrate and implement this functionality.

Learn More –

Let’s get started.

Create Database & Table

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE php_applications;

Inside this database, we need to create a table.

Table we need – countries.

CREATE TABLE `countries` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `sortname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phonecode` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Dummy Data for Application

Here, you need to copy mysql query from this given file and run into sql tab of phpmyadmin. First download it and run.

You will see something like this after this test data insertion.

Application Folder Structure

You need to create a folder structure to develop this application in PHP and MySQLi. Have a look the files this application –

Create a folder with name php-select2-multiselect and create these 2 files into it.

Database Configuration

Open dbconfig.php file from folder. Add these lines of code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How To Use Select2 for Multiple Select Tutorial
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Database configuration
$host   = "localhost";
$dbuser = "admin";
$dbpass = "Admin@123";
$dbname = "php_applications";

// Create database connection
$conn = new mysqli($host, $dbuser, $dbpass, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Application Programming

Open index.php file from application. Add these lines of code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How To Use Select2 for Multiple Select Tutorial
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Include the database configuration file 
require 'dbconfig.php';

$countrySelect = $conn->prepare("SELECT * FROM countries");

$countrySelect->execute();
$countries = $countrySelect->get_result();

$itemRecords = array();
while ($item = $countries->fetch_assoc()) {
    extract($item);
    $itemDetails = array(
        "id" => $id,
        "name" => $name
    );
    array_push($itemRecords, $itemDetails);
}
?>

<html lang="en">

<head>
    <title>PHP MySQLi How To Use Select2 for Multiple Select Tutorial</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha256-aAr2Zpq8MZ+YA/D6JtRD3xtrwpEz2IqOS+pWD/7XKIw=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha256-OFRAJNoaD8L3Br5lglV7VyLRf0itmoBzWUoM+Sji4/8=" crossorigin="anonymous"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>

<body>
    <div class="row mt-5">
        <div class="col-md-8 offset-2 mt-5">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h4>PHP MySQLi How To Use Select2 for Multiple Select Tutorial</h4>
                </div>
                <div class="card-body" style="height: 280px;">
                    <form action="#" method="post">
                        <div class="form-group">
                            <label>Country :</label>
                            <select class="dd_country related-post form-control" name="country[]" multiple>
                                <option value="">Select country</option>
                                <?php
                                if (count($itemRecords) > 0) {
                                    foreach ($itemRecords as $ct) {
                                ?>
                                        <option value="<?php echo $ct['id']; ?>"><?php echo $ct['name']; ?></option>
                                <?php
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <button class="btn btn-success store-related-post btn-sm">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $('.dd_country').select2();
        });
    </script>
</body>

</html>

Application Testing

Now,

URL: http://localhost/php-select2-multiselect/index.php

Load data in Select2 Ajax Search

Successfully, you should be able to select multi options from dropdown.

Download Complete Source Code

We hope this article helped you to Learn PHP MySQLi How To Use Select2 for Multiple Select Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.