How To Create Dynamic Bootstrap Accordion

Accordion(collapsible content) is the best way to toggle(hide and show) large content. A FAQ is one of the commonly used examples of the accordion. The accordion is used to display more data in less space. It works on a collapse-expand format. Using the accordion one can hide and see content between different sections.

Bootstrap comes with a lot of useful components that can easily be integrated on the website. One of them is accordion which we will use in this tutorial. If you wants to see how Bootstrap’s accordion works then check out example here.

In this article, I show you how to make a dynamic Bootstrap accordion. To make the dynamic accordion, we will fetch results from the database and create accordion with these records.

How to Add Static Bootstrap Accordion in Website

Adding the static Bootstrap accordion on the website is super easy. You just need to copy the source code provided by Bootstrap and place it wherever you want to display the accordion. Below is the sample code of adding a static bootstrap accordion.

<html>
<head>
    <title>Accordion Examples</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="accordion" id="accordionExample">
        <div class="card">
            <div class="card-header" id="headingOne">
                <h2 class="mb-0">
                    <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                        Collapsible Group Item #1
                    </button>
                </h2>
            </div>
            <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
                <div class="card-body">
                    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
                </div>
            </div>
        </div>
        <div class="card">
            <div class="card-header" id="headingTwo">
                <h2 class="mb-0">
                    <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                        Collapsible Group Item #2
                    </button>
                </h2>
            </div>
            <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
                <div class="card-body">
                    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

The above code will display static Bootstrap accordion on your webpage. If you prefer to use it with static content then you just need to change the title and content from the above HTML.

However, the purpose of this tutorial is to create a dynamic Bootstrap accordion. So, read on I show you how in the next steps.

Getting Started

Let’s assume you need to show faqs in accordion. For the faqs, we need a database table filled up with a few dummy entries. So, create a database called ‘bootstrap’ and run the below query to create a table inside it.

CREATE TABLE `faq` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` text NOT NULL,
 `content` text NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After creating a table, let’s add some dummy entries to it. These dummy entries will be used to create a dynamic accordion.

INSERT INTO `faq` (`id`, `title`, `content`) VALUES
(1, 'Question 1', 'This is answer 1.'),
(2, 'Question 2', 'This is answer 2.'),
(3, 'Question 3', 'This is answer 3.');

The next part is writing code for connecting a database in PHP. Create a file index.php and add connection code as shown below.

$con = mysqli_connect("localhost", "MYSQL_USERNAME", "MYSQL_PASSWORD", "bootstrap");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

Once you have connected the database successfully, fetch the result from the database table which we’ll require in a moment.

$sql = "SELECT * FROM faq ORDER BY id DESC";
$result = mysqli_query($con,$sql);

Create a Dynamic Bootstrap Accordion

You have fetched the records from the database table and assigned them to the PHP variable $result. We will loop through this variable and make things dynamic.

If you closely look at the HTML code of accordion, you will notice the same kind of markup gets repeated. While making it dynamic, we have to tweak some of the attributes like id, class, aria-expanded, aria-controls, etc in this markup.

Below is the code which generates a dynamic Bootstrap accordion.

<div class="accordion" id="accordionExample">
    <?php
    $i=1;
    while($row = mysqli_fetch_assoc($result)) {
        ?>
        <div class="card">
            <div class="card-header" id="heading<?php echo $i; ?>">
                <h2 class="mb-0">
                    <button class="btn btn-link <?php if($i>1) echo "collapsed"; ?>" type="button" data-toggle="collapse" data-target="#collapse<?php echo $i; ?>" aria-expanded="<?php echo ($i==1) ? 'true': 'false'; ?>" aria-controls="collapse<?php echo $i; ?>">
                        <?php echo $row['title']; ?>
                    </button>
                </h2>
            </div>
            <div id="collapse<?php echo $i; ?>" class="collapse <?php if($i==1) echo 'show'; ?>" aria-labelledby="heading<?php echo $i; ?>" data-parent="#accordionExample">
                <div class="card-body">
                    <?php echo $row['content']; ?>
                </div>
            </div>
        </div>
        <?php
        $i++;
    }
    ?>
</div>

Our final code is as follows.

<?php
$con = mysqli_connect("localhost", "root", "", "bootstrap");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT * FROM faq ORDER BY id DESC";
$result = mysqli_query($con,$sql);
?>

<html>
<head>
    <title>Accordion Examples</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
    <div class="accordion" id="accordionExample">
        <?php
        $i=1;
        while($row = mysqli_fetch_assoc($result)) {
            ?>
            <div class="card">
                <div class="card-header" id="heading<?php echo $i; ?>">
                    <h2 class="mb-0">
                        <button class="btn btn-link <?php if($i>1) echo "collapsed"; ?>" type="button" data-toggle="collapse" data-target="#collapse<?php echo $i; ?>" aria-expanded="<?php echo ($i==1) ? 'true': 'false'; ?>" aria-controls="collapse<?php echo $i; ?>">
                            <?php echo $row['title']; ?>
                        </button>
                    </h2>
                </div>
                <div id="collapse<?php echo $i; ?>" class="collapse <?php if($i==1) echo 'show'; ?>" aria-labelledby="heading<?php echo $i; ?>" data-parent="#accordionExample">
                    <div class="card-body">
                        <?php echo $row['content']; ?>
                    </div>
                </div>
            </div>
            <?php
            $i++;
        }
        ?>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>

That’s it! I hope you understand how to create a dynamic Bootstrap accordion. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

3 thoughts on “How To Create Dynamic Bootstrap Accordion

  1. Is there any way to do this with a nested (3-tiered) accordion – being that the id, class, aria-expanded, aria-controls, etc. have to be incremented in some way ($i++) ?

  2. very nice article and it has helped me on my website thank you so much, sir perfect solutions collapsible
    panel many people have confusion about to fetch data from database dynamically but u gave me perfect solution.

  3. Only solution that actually worked to utilize dynamic content from a database, I was able to get the accordion to work but not collapse and with this demo it is working perfect now. Thank You!

Leave a Reply

Your email address will not be published. Required fields are marked *