数据独立性和MySQL数据的使用问题。如何使用PHP解决?

问题描述 投票:0回答:1

任务: 构建当前日历月的用户注册图表(日期列显示每天的注册数量)。问题是数据并非每天都可用(注册)。如果没有日期,图表将显示该日期和列值:0。如何使用 PHP 解决此问题?

问题:仅处理有记录的那些天的数据。问题在屏幕截图中可见。

当前结果:

ScreenShoot

PHP代码:

 <?php 
  $conn = new mysqli('localhost','test','password','test');
  $query = $conn->query("
    SELECT 
    DATE(date) as monthname,
    COUNT(id) as amount
    FROM clients WHERE date BETWEEN '2023-01-09' AND '2023-01-30' 
    GROUP BY monthname 
  ");

  foreach($query as $data) {
    $month[] = $data['monthname'];
    $amount[] = $data['amount'];
  }
?>

JS代码(Chart.JS):

<script>
  const labels = <?php echo json_encode($month) ?>;
  const data = {
    labels: labels,
    datasets: [{
      label: 'Clients',
      data: <?php echo json_encode($amount) ?>,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 205, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(201, 203, 207, 0.2)'
      ],
      borderColor: [
        'rgb(255, 99, 132)',
        'rgb(255, 159, 64)',
        'rgb(255, 205, 86)',
        'rgb(75, 192, 192)',
        'rgb(54, 162, 235)',
        'rgb(153, 102, 255)',
        'rgb(201, 203, 207)'
      ],
      borderWidth: 1
    }]
  };
  const config = {
    type: 'bar',
    data: data,
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    },
  };

  var myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
</script>

SQL 请求:

SELECT DATE(date) as monthname,
COUNT(id) as amount
FROM clients WHERE date BETWEEN '2023-01-09' AND '2023-01-30' 
GROUP BY monthname 
php mysqli
1个回答
1
投票

由于你不能总是保证每个日期都有条目,所以我要做的是在 PHP 中生成日期数组,然后对每一天进行查询。

类似这样的:

$interval = DateInterval::createFromDateString('1 day');
$daterange = new DatePeriod('2023-01-09', $interval, '2023-01-30');

foreach($daterange as $date) {
    $query = "SELECT COUNT(id) AS amount
              FROM clients
              WHERE date=$date->format('Y-m-d')";
    // Do your logic here
    // I am not sure how you handle your data, but
    // I like using an array with the date as key
    $data[$date->format('Y-m-d')] = $queryResult;
}

您可以在

DateInterval
此处

查看文档
© www.soinside.com 2019 - 2024. All rights reserved.