ChartJS 在 X 轴上显示不正确的数据

ChartJS showing incorrect data on the X-Axes

我需要 ChartJS 方面的帮助,它显示了我的 MySQL 数据库中甚至不存在的几个月的数据。我数据库里有8月和9月的数据,其余月份没有数据,为什么显示其他月份的数据?

这是带有 ChartJS 的仪表板的更新视图

Ecems Dashboard

这是我的MySQLTable内容:

MySQL Database

我的 index.php 文件:

<?php include 'settings.php'; //include settings ?>

<body class="crm_body_bg">
<!-- main content part here -->
<section class="main_content dashboard_part">
        <!-- menu  -->
    <div class="container-fluid no-gutters">
        <div class="row">
            <div class="col-lg-12 p-0 ">
                <div class="header_iner d-flex justify-content-between align-items-center">
                    <div class="sidebar_icon d-lg-none">
                        <i class="ti-menu"></i>
                    </div>
                    <div class="serach_field-area">
                            <div class="search_inner">
                                <form action="#">
                                    <div class="search_field">
                                        <input type="text" placeholder="Search here..." >
                                    </div>
                                    <button type="submit"> <img src="img/icon/icon_search.svg" alt=""> </button>
                                </form>
                            </div>
                        </div>
                    <div class="header_right d-flex justify-content-between align-items-center">
                    <div class="profile_info">
                             <img src="../../img/<?php $ufunc->UserName(); //Show name who is in session user?>.jpg" alt="#">
                            <div class="profile_info_iner">
                                <div class="profile_author_name">
                                <h5><?php $ufunc->UserName(); //Show name who is in session user?></h5>
                                </div>
                                <div class="profile_info_details">
                                    <a href="#">My Profile </a>
                                    <a href="#">Settings</a>
                                   <a href="../../includes/logout.php">Logout</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--/ menu  -->
    <div class="main_content_iner ">
        <div class="container-fluid p-0 sm_padding_15px">
            <div class="row justify-content-center">
                <div class="col-12">
                    <div class="dashboard_header mb_50">
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="dashboard_header_title">
                                    <h3>ECEMS v2.0 Administration Dashboard</h3>
                                    <h6>Logged in as: <?php $ufunc->UserName(); //Show name who is in session user?></h6>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="dashboard_breadcam text-right">
                                    <p><a href="#">Dashboard</a></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6 col-xl-6">
                    <div class="white_box mb_30">
                        <div class="box_header">
                            <div class="main-title">
                                <h3 class="mb_25" >General Recyclables Processing Overview</h3>
                            </div>
                           
                        </div>
            
                                    <canvas id="general-recyclables"></canvas>
                       
                    </div>
                </div>
                  
                  <div class="col-lg-6 col-xl-6">
                    <div class="white_box mb_30">
                        <div class="box_header">
                            <div class="main-title">
                                <h3 class="mb_25" >Printed Circuit Boards Processing Overview</h3>
                            </div>
                        
                        </div>
            
                                    <canvas id="general-recyclables2"></canvas>
                       
                    </div>
                </div>
                   <div class="col-lg-4 col-xl-4">
                    <div class="white_box mb_30">
                        <div class="box_header">
                            <div class="main-title">
                                <h3 class="mb_25" >Targets for <?php echo date('F Y'); ?></h3>
                            </div>
                          
                        </div>
            <h3>Target: 12000KG</h3>
            <h3>Current Value:  <?php
$dbConnection = new PDO('mysql:dbname=ecemsmaster;host=127.0.0.1;charset=utf8', 'ecemsmaster', 'ecemsmaster');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//The COUNT SQL statement that we will use.
$sql = "SELECT SUM(subgrade ++ castaluminium ++ copper ++ stainlesssteel ++ plastic ++ batteries ++ brass ++ cables ++ lowgradePCB ++ mediumgradePCB ++ highgradePCB) AS num FROM daily_recyclables where MONTH(date)=MONTH(curdate());";

//Prepare the COUNT SQL statement.
$stmt = $dbConnection->prepare($sql);

//Execute the COUNT statement.
$stmt->execute();

//Fetch the row that MySQL returned.
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//The $row array will contain "num". Print it out.
echo $row['num'];
?> KG</h3>
            <h3>Over/Under Target: -1000KG</h3>
            
            <br>
           
                       
                    </div>
                </div>
              <div class="col-lg-4 col-xl-4">
                    <div class="white_box mb_30">
                        <div class="box_header">
                            <div class="main-title">
                                <h3 class="mb_25" >Previous Month</h3>
                            </div>
                          
                        </div>
            <h3>Target: 12000KG</h3>
            <h3>Previous Value:  <?php
$dbConnection = new PDO('mysql:dbname=ecemsmaster;host=127.0.0.1;charset=utf8', 'ecemsmaster', 'ecemsmaster');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//The COUNT SQL statement that we will use.
$sql = "SELECT SUM(subgrade ++ castaluminium ++ copper ++ stainlesssteel ++ plastic ++ batteries ++ brass ++ cables ++ lowgradePCB ++ mediumgradePCB ++ highgradePCB) AS num FROM daily_recyclables where MONTH(date)=MONTH(curdate())-1;";

//Prepare the COUNT SQL statement.
$stmt = $dbConnection->prepare($sql);

//Execute the COUNT statement.
$stmt->execute();

//Fetch the row that MySQL returned.
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//The $row array will contain "num". Print it out.
echo $row['num'];
?> KG</h3>
            <h3>Over/Under Target: -1000KG</h3>
            
            <br>
           
                       
                    </div>
                </div>
               
            </div>
        </div>
    </div>
    
<?php
require '../../includes/global_footer.html'; //include Global Footer
?>

这是我的 UPDATED linegraph.js 文件,基于 rustyBucketBay 回答 15/10/2021

  $(document).ready(function(){
  $.ajax({
    url : "http://www.ecems.co.za/ecemsv2/user/admin/data.php",
    type : "POST",
    success : function(data){
      console.log(data);

     
      var date = [];
      var subgrade_material = [];
       var castaluminium_material = [];
      var copper_material = [];
       var stainlesssteel_material = [];
        var plastic_material = [];
         var batteries_material = [];
          var brass_material = [];
           var cables_material = [];
           

      for(var i in data) {
        date.push("" + data[i].date);
        subgrade_material.push(data[i].subgrade);
        castaluminium_material.push(data[i].castaluminium);
         copper_material.push(data[i].copper);
          stainlesssteel_material.push(data[i].stainlesssteel);
           plastic_material.push(data[i].plastic);
            batteries_material.push(data[i].batteries);
            brass_material.push(data[i].brass);
              cables_material.push(data[i].cables);
             
      }
var barChartData = {
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    datasets: [
      {
        label: "Subgrade",
        backgroundColor: "rgba(189,55,220,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
       {
        label: "Cast Aluminium",
        backgroundColor: "rgba(89,155,120,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
      {
        label: "Copper",
        backgroundColor: "rgba(100,105,20,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
       {
        label: "Stainless Steel",
        backgroundColor: "rgba(2,15,12,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
       {
        label: "Brass",
        backgroundColor: "rgba(99,99,120,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
      // {
      //   label: "Copper",
      //   backgroundColor: "rgba(129,155,20,0.5)",
      //   data: copper_material
      // },
      // {
      //   label: "Stainless Steel",
      //   backgroundColor: "rgba(29,255,55,0.5)",
      //   data: stainlesssteel_material
      // },
      // {
      //   label: "Brass",
      //   backgroundColor: "rgba(0,155,45,0.5)",
      //   data: brass_material
      // }
    ]
  };

var ctx = document.getElementById("general-recyclables").getContext("2d");
var myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
   
    options: {
        title: {
            display: true,
            text: "General Recyclables Overview By Month"
        },
      
        responsive: true,
        scales: {
            xAxes: [{
                stacked: true,
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});

   
      
      
    },
    
    error : function(data) {

    }
    
  });
  
});
$(document).ready(function(){
  $.ajax({
    url : "http://www.ecems.co.za/ecemsv2/user/admin/data.php",
    type : "POST",
    success : function(data){
      console.log(data);

     
      var date = [];
      var lowgradePCB = [];
       var mediumgradePCB = [];
      var highgradePCB = [];
   

      for(var i in data) {
        date.push("" + data[i].date);
        lowgradePCB.push(data[i].lowgradePCB);
        mediumgradePCB.push(data[i].mediumgradePCB);
        highgradePCB.push(data[i].highgradePCB);
       
      }
var barChartData = {
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    datasets: [
      {
        label: "Low Grade PCB",
        backgroundColor: "rgba(27,27,235,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
       {
        label: "Medium Grade PCB",
        backgroundColor: "rgba(20,170,235,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
      {
        label: "High Grade PCB",
        backgroundColor: "rgba(20,235,34,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]
      },
    
    ]
  };

var ctx = document.getElementById("general-recyclables2").getContext("2d");
var myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
   
    options: {
        title: {
            display: true,
            text: "Printed Circuit Board Processing Overview"
        },
      
        responsive: true,
        scales: {
            xAxes: [{
                stacked: true,
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});

   
      
      
    },
    
    error : function(data) {

    }
    
  });
  
});

这是我的 data.php 文件:

<?php

header('Content-Type: application/json');

//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'REDACTED');
define('DB_PASSWORD', 'REDACTED');
define('DB_NAME', 'REDACTED');

//get mysqliection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
    die("connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT recID,date,subgrade,castaluminium,copper,stainlesssteel,plastic,batteries,brass,cables,lowgradePCB,mediumgradePCB,highgradePCB FROM daily_recyclables");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close mysqliection
$mysqli->close();

//now print the data
print json_encode($data);


?>

尝试修改日期格式问题, 检查日期 Date.UTC()

例如,在下面的代码片段中使用您的简化图表。每个月的数据按索引分配给图表。

标签:[“一月”、“二月”、....]
数据:[100, 200, ....]

100 表示 1 月,200 表示 2 月,依此类推。

我的意思是,您需要传递一个数组,其中数组中的数据已经按月分组,或者您“硬编码”的数组,或者使用代码进行相应的安排以使用日期检索该数组您数据库的字段

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>

<canvas id="chart"></canvas>
<script>
  var barChartData = {
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    datasets: [
      {
        label: "Subgrade",
        backgroundColor: "rgba(189,55,220,0.5)",
        data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100]
      }
      // {
      //   label: "Cast Aluminium",
      //   backgroundColor: "rgba(29,155,220,0.5)",
      //   data: castaluminium_material
      // },
      // {
      //   label: "Copper",
      //   backgroundColor: "rgba(129,155,20,0.5)",
      //   data: copper_material
      // },
      // {
      //   label: "Stainless Steel",
      //   backgroundColor: "rgba(29,255,55,0.5)",
      //   data: stainlesssteel_material
      // },
      // {
      //   label: "Brass",
      //   backgroundColor: "rgba(0,155,45,0.5)",
      //   data: brass_material
      // }
    ]
  };

  var ctx = document.getElementById("chart").getContext("2d");
  var myBar = new Chart(ctx, {
    type: "bar",
    data: barChartData,
    options: {
      title: {
        display: true,
        text: "General Recyclables Overview By Month"
      },
      tooltips: {
        mode: "label"
        // callbacks: {
        //   label: function (tooltipItem, data) {
        //     var corporation = data.datasets[tooltipItem.datasetIndex].label;
        //     var valor =
        //       data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        //     var total = 0;
        //     for (var i = 0; i < data.datasets.length; i++)
        //       total += data.datasets[i].data[tooltipItem.index];
        //     if (tooltipItem.datasetIndex != data.datasets.length - 1) {
        //       return (
        //         corporation +
        //         " : KG" +
        //         valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ",")
        //       );
        //     } else {
        //       return [
        //         corporation +
        //           " :" +
        //           valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ","),
        //         "Total : " + total + " KG"
        //       ];
        //     }
        //   }
        // }
      },
      responsive: true,
      scales: {
        xAxes: [
          {
            stacked: true
          }
        ],
        yAxes: [
          {
            stacked: true
          }
        ]
      }
    }
  });

  var barChartData = {
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    datasets: [
      {
        label: "Low Grade PCB",
        backgroundColor: "rgba(189,55,220,0.5)",
        data: lowgradePCB_material
      },
      {
        label: "Medium Grade PCB",
        backgroundColor: "rgba(29,155,220,0.5)",
        data: mediumgradePCB_material
      },
      {
        label: "Copper",
        backgroundColor: "rgba(129,155,20,0.5)",
        data: highgradePCB_material
      }
    ]
  };

  var ctx = document.getElementById("general-recyclables2").getContext("2d");
  var myBar = new Chart(ctx, {
    type: "bar",
    data: barChartData,
    options: {
      title: {
        display: true,
        text: "Printed Circuit Board Processing"
      },
      tooltips: {
        mode: "label",
        callbacks: {
          label: function (tooltipItem, data) {
            var corporation = data.datasets[tooltipItem.datasetIndex].label;
            var valor =
              data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
            var total = 0;
            for (var i = 0; i < data.datasets.length; i++)
              total += data.datasets[i].data[tooltipItem.index];
            if (tooltipItem.datasetIndex != data.datasets.length - 1) {
              return (
                corporation +
                " : KG" +
                valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ",")
              );
            } else {
              return [
                corporation +
                  " :" +
                  valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ","),
                "Total : " + total + " KG"
              ];
            }
          }
        }
      },
      responsive: true,
      scales: {
        xAxes: [
          {
            stacked: true
          }
        ],
        yAxes: [
          {
            stacked: true
          }
        ]
      }
    }
  });
</script>