Chartjs-How to displays item names from the database using a monthly or yearly chart PHP MySQL

0👍

Your SQL query very poor and unreadable. If you are using too much if/else you are wrong way. Just use native functions.

PDO example;

$host = 'localhost';
$username = 'root';
$password = '';
$db_name = 'market_db';

$conn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

// trim for sql query, 01 -> 1
$_POST['month1'] = ltrim($_POST['month1'] ?: '1', '0');
$_POST['month2'] = ltrim($_POST['month2'] ?: '12', '0');

// By month

// only between months
if(isset($_POST['year1']) && $_POST['year1'] == null){
    $query = $conn->prepare("SELECT *, MONTHNAME(mydate) AS month_name, YEAR(mydate) AS year, COUNT(*) AS item_count 
    FROM mytable WHERE MONTH(mydate) BETWEEN :month1 AND :month2 GROUP BY MONTH(mydate)");

    $query->bindParam(':month1', $_POST['month1'], PDO::PARAM_INT);
    $query->bindParam(':month2', $_POST['month2'], PDO::PARAM_INT);
    $query->execute();
    $result_months = $query->fetchAll();
}
// between months with selected year
else {
    $query = $conn->prepare("SELECT *, MONTHNAME(mydate) AS month_name, YEAR(mydate) AS year, COUNT(*) AS item_count 
    FROM mytable WHERE MONTH(mydate) BETWEEN :month1 AND :month2 AND YEAR(mydate) = :year1 GROUP BY MONTH(mydate)");

    $query->bindParam(':month1', $_POST['month1'], PDO::PARAM_INT);
    $query->bindParam(':month2', $_POST['month2'], PDO::PARAM_INT);
    $query->bindParam(':year1', $_POST['year1'], PDO::PARAM_INT);
    $query->execute();
    $result_months = $query->fetchAll();
}

Then print as json array.

const byMonthData = [<?php foreach($result_months as $item) echo json_encode($item).','?>];

Use array map or filter.

labels: byMonthData.map(function (item) {
    return [
        [`${item.month_name} ${item.year}`],
        [`Item: ${item.item}`]
    ]
}),

Complete example

const byMonthData = [<?php foreach($result_months as $item) echo json_encode($item).','?>];

var ctx = document.getElementById("myChart_month");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: byMonthData.map(function (item) {
            return [
                [`${item.month_name} ${item.year}`],
                [`Item: ${item.item}`]
            ]
        }),
        datasets: [{
            label: "item",
            data: byMonthData.map(function (item) {
                return item.item_count
            }),
            backgroundColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        },
    }
});

Result

enter image description here

Leave a comment