How to Create Dynamic Stacked Bar, Doughnut, and Pie Charts in PHP with Chart.js
- Setting up the environment
Before we get started, make sure you have PHP and a local web server installed (e.g., Apache or Nginx). Then, create a new PHP file (e.g., chart.php
) and include the Chart.js library in your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Charts with PHP and Chart.js</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</body>
</html>
2. Prepare the data
Next, you need to fetch the data from your database or data source. For simplicity, we’ll create a dummy dataset in PHP arrays. You can replace this data with your actual data from your database or API.must fetch the data from your database or
<?php
$data = [
"labels" => ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
"datasets" => [
[
"label" => "Votes",
"data" => [12, 19, 3, 5, 2, 3],
"backgroundColor" => [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
"borderColor" => [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
"borderWidth" => 1
]
]
];
?>
3. Creating the canvas elements
Now, create the canvas elements where the charts will be displayed:
<!-- Add this code within the <body> tag -->
<div>
<canvas id="barChart"></canvas>
<canvas id="doughnutChart"></canvas>
<canvas id="pieChart"></canvas>
</div>
5.. Implement the charts with Chart.js
Finally, create the stacked bar, doughnut, and pie charts using the prepared data and Chart.js:
<!-- Add this code just before the closing </body> tag -->
<script>
// Pass the PHP data to JavaScript
const data = <?php echo json_encode($data); ?>;
// Stacked Bar Chart
const barChart = new Chart(document.getElementById("barChart"), {
type: "bar",
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins: {
title: {
display: true