Home >Backend Development >PHP Tutorial >How to use PHP database connection for data analysis and statistics
How to use PHP database connection for data analysis and statistics
Introduction:
In the modern data-driven world, data analysis and statistics have become crucial . PHP, as a popular server-side scripting language, is also widely used in data processing and analysis. This article will introduce how to use PHP database connection for data analysis and statistics, and help readers understand the specific implementation details through code examples.
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "database"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功";
$sql = "SELECT COUNT(*) as total FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出数据 while($row = $result->fetch_assoc()) { echo "用户数量: " . $row["total"]; } } else { echo "没有找到结果"; }
$sql = "SELECT gender, COUNT(*) as total FROM users GROUP BY gender"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出数据 while($row = $result->fetch_assoc()) { echo "性别: " . $row["gender"]. " - 人数: " . $row["total"]; } } else { echo "没有找到结果"; }
<!DOCTYPE html> <html> <head> <title>用户年龄分布</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <canvas id="myChart"></canvas> <script> <?php $sql = "SELECT age, COUNT(*) as total FROM users GROUP BY age"; $result = $conn->query($sql); $ages = []; $totals = []; if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $ages[] = $row["age"]; $totals[] = $row["total"]; } } else { echo "没有找到结果"; } ?> // 创建柱状图 var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: <?php echo json_encode($ages); ?>, datasets: [{ label: '人数', data: <?php echo json_encode($totals); ?>, backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </body> </html>
Summary:
By using PHP database connection, we can easily perform data analysis and statistics. In this article, we learned how to connect to a database, query data, perform data analysis and statistics, and display the results through data visualization. Mastering these skills can help us better understand and utilize data and achieve more accurate data-driven decisions. I hope this article can provide some help to readers in their learning and practice of PHP data analysis and statistics.
The above is the detailed content of How to use PHP database connection for data analysis and statistics. For more information, please follow other related articles on the PHP Chinese website!