doukan1258 2016-11-02 08:08
浏览 85

如何使用数据库值绘制条形图

I have some value in my database. I want to make a chart with these values summary.

Here is my PHP code to connect database:

<?php
header('Content-Type: text/html; charset=utf-8');

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

//get connection
$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 SUM(akim) FROM etkin GROUP BY YEAR(tarih),MONTH(tarih)");

//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 connection
$mysqli->close();

echo json_encode($data);
?>

This code output is:

[{"SUM(akim)":"851"},{"SUM(akim)":"64"}]

Now I have script to draw chart. Here is my script code:

<script>
    $(document).ready(function(){
    var data = <?php echo json_encode($data) ?>;

            var akim = [];

            for(var i in data) {
                akim.push(data[i].SUM(akim));
            }

                var chartdata = {
                    labels: id,
                    datasets : [
                        {
                            label: 'akim',
                            backgroundColor: 'rgba(200, 200, 200, 0.75)',
                            borderColor: 'rgba(200, 200, 200, 0.75)',
                            hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                            hoverBorderColor: 'rgba(200, 200, 200, 1)',
                            data: akim
                        }
                    ]
                };

                var ctx = $("#mycanvas1");

                var barGraph = new Chart(ctx, {
                    type: 'bar',
                    data: chartdata
                });
        });
    </script>

Where I am wrong? I think it should work, but it's not working.

  • 写回答

1条回答 默认 最新

  • doukanxi4246 2016-11-02 09:22
    关注

    This functionality can be achieved using a javascript library called ChartJs. You can read the documentation for more details. http://www.chartjs.org/docs/#bar-chart-introduction

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line