Dynamic Traffic Analytics Dashboard
Custom analytics system tracking page views, sessions, and traffic sources with Chart.js visualization.
javascript - manage_traffic.php
// Fetch analytics data via PHP
$stmt = $conn->prepare("
SELECT
DATE(view_time) as date,
COUNT(*) as views,
COUNT(DISTINCT session_id) as sessions
FROM page_views
WHERE view_time >= DATE_SUB(NOW(), INTERVAL ? DAY)
GROUP BY DATE(view_time)
ORDER BY date ASC
");
$stmt->bind_param("i", $days);
$stmt->execute();
$result = $stmt->get_result();
$dates = [];
$views = [];
$sessions = [];
while ($row = $result->fetch_assoc()) {
$dates[] = $row['date'];
$views[] = $row['views'];
$sessions[] = $row['sessions'];
}
// JavaScript - Render with Chart.js
const ctx = document.getElementById('trafficChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($dates); ?>,
datasets: [{
label: 'Page Views',
data: <?php echo json_encode($views); ?>,
borderColor: 'rgb(88, 166, 255)',
backgroundColor: 'rgba(88, 166, 255, 0.1)',
tension: 0.4
}, {
label: 'Unique Sessions',
data: <?php echo json_encode($sessions); ?>,
borderColor: 'rgb(63, 185, 80)',
backgroundColor: 'rgba(63, 185, 80, 0.1)',
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: { beginAtZero: true, ticks: { color: '#8b949e' } }
},
plugins: {
legend: { labels: { color: '#c9d1d9' } }
}
}
});
💡 What Makes This Special
This analytics system demonstrates full-stack integration: PHP queries aggregate data from the database using GROUP BY for efficient counts, json_encode() safely passes data to JavaScript, and Chart.js renders responsive visualizations. The key insight is using COUNT(DISTINCT session_id) to track unique visitors versus total page views. The Chart.js configuration uses CSS variable colors (converted to RGB) to match the site's design system. This pattern scales to complex dashboards—I use the same approach for device stats, geographic data, and referral sources.