How To Create A Dynamic Bar Chart In PHP And MySQL Using Charts.js

Introduction

Bar charts are a great way to display categorical data, making it easy to compare values across different categories. With PHP and MySQL, you can create a dynamic bar chart in php that updates in real-time as data changes in the database. In this tutorial, we’ll show you how to create a dynamic bar chart using PHP, MySQL, and Chart.js.

Prerequisites for Creating A Dynamic Bar Chart In PHP

To get started, ensure you have:

  1. A working PHP and MySQL server (like XAMPP, WAMP, or LAMP).
  2. Basic knowledge of PHP and MySQL.
  3. Chart.js library for rendering charts in the browser.

Step 1: Create the Database and Table

First, create a database and a table in MySQL to hold the data you want to display. For this example, we’ll create a table that stores sales data for different products.

CREATE DATABASE chart_data;
USE chart_data;

CREATE TABLE product_sales (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100),
    sales INT
);

INSERT INTO product_sales (product_name, sales) VALUES 
('Product A', 150),
('Product B', 200),
('Product C', 300),
('Product D', 250),
('Product E', 100);

This table has three columns:

  • id: Unique identifier for each entry.
  • product_name: Name of each product.
  • sales: Sales figures for each product.

Step 2: Connect to MySQL Database in PHP

Next, create a PHP file to connect to the MySQL database. We’ll use this connection to retrieve data from the product_sales table.

<?php
    $host = 'localhost';
    $db = 'chart_data';
    $user = 'root';
    $password = '';
    
    try {
        $conn = new PDO("mysql:host=$host;dbname=$db", $user, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
?>

This script uses PDO to securely connect to the MySQL database.

Step 3: Fetch Data from the Database

Retrieve data from the product_sales table and format it for the bar chart.

<?php
    // Fetch data
    $stmt = $conn->prepare("SELECT product_name, sales FROM product_sales");
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Separate data into labels and values
    $labels = [];
    $values = [];
    foreach ($data as $row) {
        $labels[] = $row['product_name'];
        $values[] = $row['sales'];
    }
    
    // Convert PHP arrays to JavaScript
    $labels_json = json_encode($labels);
    $values_json = json_encode($values);
?>

This PHP script fetches all rows from the table, then organizes the data into labels (product names) and values (sales figures) for use in the bar chart.

Step 4: Display the Bar Chart Using Chart.js

Now, add the HTML and JavaScript to render the bar chart with Chart.js.

1.Include Chart.js – Add this script to include the Chart.js library in your HTML file.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

2.Create a Canvas Element – The bar chart will render inside this <canvas> element.

<div>
    <canvas id="myBarChart"></canvas>
</div>

3.Generate the Chart – Use JavaScript to create the bar chart with the data from PHP.

<script>
    // Get data from PHP
    var labels = <?php echo $labels_json; ?>;
    var values = <?php echo $values_json; ?>;

    // Create bar chart
    var ctx = document.getElementById('myBarChart').getContext('2d');
    var myBarChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Product Sales',
                data: values,
                backgroundColor: 'rgba(54, 162, 235, 0.6)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

Here’s what each part does:

  • labels and values contain the data fetched from PHP.
  • backgroundColor and borderColor set the color of the bars.
  • beginAtZero ensures that the y-axis starts at zero, making it easier to compare values.

Step 5: Test Your Chart

Save and open your PHP file in a browser. If everything is set up correctly, you should see a dynamic bar chart that displays the sales data for each product from your MySQL database.

Step 6: Make the Chart Dynamic with AJAX (Optional)

To automatically update your chart without refreshing the page, you can use AJAX to fetch updated data at intervals.

1.Create a PHP file (data.php) to return the data in JSON format.

<?php
    header('Content-Type: application/json');
    include 'db_connection.php';
    
    $stmt = $conn->prepare("SELECT product_name, sales FROM product_sales");
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($data);
?>

2.Use AJAX to Update Chart Data in your main file.

setInterval(function() {
    fetch('data.php')
        .then(response => response.json())
        .then(data => {
            var labels = data.map(item => item.product_name);
            var values = data.map(item => item.sales);

            myBarChart.data.labels = labels;
            myBarChart.data.datasets[0].data = values;
            myBarChart.update();
        });
}, 5000); // Refresh every 5 seconds

This AJAX script will fetch updated data from data.php and refresh the chart without reloading the page.

Conclusion

Creating a dynamic bar chart with PHP and MySQL allows you to visualize data in real time, which is ideal for dashboards, reports, and performance tracking. Chart.js makes it easy to design a responsive and visually appealing chart that can be easily integrated into your web application.

FAQs

Q: Can I customize the colors and style of the bar chart?
A: Yes, you can adjust the backgroundColor and borderColor properties in the dataset.

Q: Is it possible to add multiple datasets?
A: Absolutely! Just add more datasets in the data object for comparing multiple categories on the same chart.

Q: How can I display large datasets?
A: For large datasets, aggregate data on the server side or use pagination to limit data displayed on the chart.

Final Thoughts

Using PHP, MySQL, and Chart.js, you can create dynamic bar charts to visualize your data in real-time. Experiment with different styles and options in Chart.js to make your bar charts even more interactive and tailored to your specific needs. Happy coding!

How To Create A Dynamic Pie Chart In PHP And MySQL Using Charts.js – Kodeao

Leave a comment