Мне нужна помощь с ChartJS, он показывает данные за несколько месяцев, которых даже нет в моей базе данных MySQL. У меня в базе есть данные за август и сентябрь, по остальным месяцам данных нет, почему отображаются данные за другие месяцы?

Вот ОБНОВЛЕННЫЙ вид панели управления с ChartJS

Панель управления Ecems

Вот моя таблица MySQL:

База данных MySQL

Мой файл 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
?>

Вот мой ОБНОВЛЕННЫЙ файл 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);


?>
0
Refurb SA 15 Окт 2021 в 11:54

2 ответа

Лучший ответ

См., Например, упрощенный график во фрагменте ниже. Данные за каждый месяц размещены индексом на графике.

Ярлыки: ["Январь", "Февраль", ....]
данные: [100, 200, ....]

Итак, 100 - январь, 200 - февраль и так далее.

Я имею в виду, что вам нужно передать массив с данными в массиве, уже сгруппированном по месяцам, либо массив, «жестко запрограммированный» вами, либо принять соответствующие меры с кодом для извлечения этого массива с использованием поля даты вашей базы данных.

<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, "$1,")
        //       );
        //     } else {
        //       return [
        //         corporation +
        //           " :" +
        //           valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"),
        //         "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, "$1,")
              );
            } else {
              return [
                corporation +
                  " :" +
                  valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"),
                "Total : " + total + " KG"
              ];
            }
          }
        }
      },
      responsive: true,
      scales: {
        xAxes: [
          {
            stacked: true
          }
        ],
        yAxes: [
          {
            stacked: true
          }
        ]
      }
    }
  });
</script>
0
rustyBucketBay 15 Окт 2021 в 09:53

Попробуйте изменить проблемы с форматом даты , дата проверки Date.UTC()

0
KWJ william 15 Окт 2021 в 09:09