Generating Dynamic Line Charts & Graph Reports Using Chart.js and PHP

Generating Dynamic Line Charts & Graph Reports Using Chart.js and PHP
Published Oct 02,2024 by Kailash Singh
0 Comment 334 Views
Creating dynamic line charts and graph reports using Chart.js and PHP is a great way to visualize data. Below is a step-by-step guide to help you get started.
Step 1: Creating Your Database
Create a database and a table to hold your data. Here’s an example SQL statement to create a simple table for storing data points:
CREATE TABLE `chart` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`label` VARCHAR(50) NOT NULL,
`value` FLOAT NOT NULL,
PRIMARY KEY (`id`)
);
Step 2: Inserting Sample Data
You can insert some sample data into your table:
INSERT INTO `data_points` (`label`, `value`) VALUES
('January', 10),
('February', 20),
('March', 30),
('April', 25),
('May', 15);
Step 3: Create PHP Script to Fetch Data
Create a PHP script (data.php) to fetch the data from the database and return it in JSON format.
<?php
$servername = "localhost"; // your server name
$username = "username"; // your database username
$password = "password"; // your database password
$dbname = "your_database"; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data
$sql = "SELECT label, value FROM chart";
$result = $conn->query($sql);
$data = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
// Return JSON data
header('Content-Type: application/json');
echo json_encode($data);
?>
Step 4: Create Your HTML and Chart.js Setup
Create an HTML file (index.php) to display the chart.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Line Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
async function fetchData() {
const response = await fetch('data.php');
const data = await response.json();
const labels = data.map(item => item.label);
const values = data.map(item => item.value);
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'My Data',
data: values,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
fetchData();
</script>
</body>
</html>
Comments ( 0 )
Elevenstech Web Tutorials
Elevenstech Web Tutorials helps you learn coding skills and enhance your skills you want.
As part of Elevenstech's Blog, Elevenstech Web Tutorials contributes to our mission of “helping people learn coding online”.
Read More
Newsletter
Subscribe to get the latest updates from Elevenstech Web Tutorials and stay up to date