简体   繁体   English

mysql sum查询chart.js

[英]mysql sum query for chartjs

Below is my code to display an array of date and amount. 下面是我的代码,用于显示日期和金额的数组。 It will be used as datasets in chart.js 它将用作chart.js中的数据集

The date was properly displayed as Apr,2018 May,2018 Jun,2018 日期已正确显示为2018年4月2018年5月2018年6月

But the amount shows only one record. 但金额仅显示一个记录。

I tried to run the query in mysql. 我试图在mysql中运行查询。 It gives correct table. 它给出正确的表。

The echo in the code is use to confirm correct record. 代码中的回显用于确认正确的记录。

I need to display : "Apr,2018", "May,2018", "June,2018" 我需要显示: “ 2018年4月”,“ 2018年5月”,“ 2018年6月”

250.65, 278, 300 250.65、278、300

which will be used as datasets for chart.js 将用作chart.js的数据集

<?php
    $sql = mysqli_query($mysqli, "SELECT DATE_FORMAT(trip_start,'%Y-%m') as trip_start1, sum(fare_amount) as income
        FROM trip
        WHERE trip_start IS NOT NULL
        GROUP BY trip_start1
        ORDER by trip_start1"
    );
    while($row = mysqli_fetch_array($sql)){
        $fare_amount = $row['income'];
        $date = date('M, Y', strtotime($row['trip_start1']));
        $dates = $dates.'"'.$date.'",';
        $fare_amount= $fare_amount.', '.$fare_amount.',';
    }
    $dates = trim($dates, ",");
    $fare_amount = trim($fare_amount, ",");
    echo $dates . '<br/>' ; //just to confirm if it will display correct array
    echo $fare_amount; //just to confirm if it will display correct array
?>

Here is my db: 这是我的数据库:

CREATE TABLE IF NOT EXISTS `trip` (
    `id` int(10) unsigned NOT NULL,
    `driver_id` int(10) unsigned NOT NULL,
    `passenger_id` int(10) unsigned NOT NULL,
    `source` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `destination` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `trip_start` timestamp NULL DEFAULT NULL,
    `trip_end` timestamp NULL DEFAULT NULL,
    `fare_amount` double DEFAULT NULL,
    `status` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
    `payment_mode` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
    CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `trip` (`id`, `driver_id`, `passenger_id`, `source`, `destination`, `trip_start`, `trip_end`, `fare_amount`, `status`, `payment_mode`, `created_at`, `updated_at`) 
VALUES(5, 6, 1, '14.6760413', '121.0437003', '2018-04-07 08:01:00', '2018-04-07 09:00:00', 250.65, 'complete', 'cash', '2018-04-06 23:06:43', '2018-04-13 02:28:21'),
(6, 6, 2, '15.6760413', '122.0437003', '2018-05-08 16:11:00', '2018-04-07 17:03:00', 278, 'complete', 'cash', '2018-04-06 23:06:43', '2018-04-14 03:40:58'),
(8, 6, 3, '14.634787799999998,121.0683213', '14.5377516,121.00137940000002', '2018-06-12 16:00:00', NULL, 100, 'booked', 'cash', '2018-04-11 10:51:16', '2018-04-14 03:44:41'),
(9, 6, 3, '14.634787799999998,121.0683213', '14.5377516,121.00137940000002', '2018-06-12 16:00:00', NULL, 100, 'booked', 'cash', '2018-04-11 11:08:43', '2018-04-14 03:45:59'),
(10, 6, 3, '14.634787799999998,121.0683213', '14.5377516,121.00137940000002', '2018-06-28 16:00:00', NULL, 100, 'booked', 'cash', '2018-04-11 11:10:12', '2018-04-14 03:46:37');

My code to display the chart: 我的代码显示图表:

        <div><h1>Budget Charts</h1></div>
        <div style="width:60%"><canvas id="Chart" ></canvas></div>
        <!-- jQuery cdn -->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
        <!-- Chart.js cdn -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
    </body>
</html>
<script> // chart DOM Element
    var ctx = document.getElementById("Chart");
    var data = {
        datasets: [{
            data: [<?php echo $fare_amount; ?>],
            backgroundColor: 'transparent',
            //backgroundColor: 'rgba(69, 92, 115, 0.5)',
            //backgroundColor: 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ', 0.4)',
            //backgroundColor: "#455C73",
            borderColor: "#39a",
            borderWidth: 5,
            label: 'Revenue' // for legend
        }],
        labels: [<?php echo $dates; ?>]
    };
    var xChart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'line',
        // The data for our dataset
        data: data,
        // Configuration options go here
        options: {
            legend: {
                display: true,
                position: 'left',
                labels: {
                    fontColor: 'black'
                    //fontColor: 'rgb(255, 99, 132)'
                }
            },
            tooltips: {mode: 'y'},
            scales: {
                yAxes: [{
                    ticks: {beginAtZero: true}
                }],
                xAxes: [{
                    ticks: {
                        autoskip: true,
                        maxTicksLimit:6
                    }
                }]
            }
        }
    });
</script>

Base approach for preparing data for js codes is to gather data in array, json_encode this array to string and output this string: 为js代码准备数据的基本方法是收集数组中的数据,将数组json_encode编码为字符串并输出此字符串:

$sql = mysqli_query($mysqli, "SELECT DATE_FORMAT(trip_start,'%Y-%m') as
trip_start1,  fare_amount as income
FROM trip
WHERE trip_start IS NOT NULL
GROUP BY trip_start1
ORDER by trip_start1");

$data = [
    'amounts' => [],
    'dates' => [],
];
while($row = mysqli_fetch_array($sql)){
    $data['amounts'][]    = $row['income'];
    $data['dates'][]      =  date('M, Y', strtotime($row['trip_start1']));
}

// merge subarrays into single one to get output as you want
$data = array_merge($data['amounts'], $data['dates']);

echo json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM