1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPでDBから配列を取り出し、jsに渡して、chart.jsでグラフ作成

Posted at

caledar_tableにあるTUTORというカラムの数をカウントし、グラフにする。

$sql = "SELECT TUTOR,COUNT(TUTOR) AS COUNT FROM CALENDAR_TABLE GROUP BY TUTOR ORDER BY COUNT DESC";
$stmt = $pdo->prepare($sql);
$status = $stmt->execute();

$res = $pdo->query($sql);
//取得したデータを全てフェッチする
$data = $res->fetchAll();
var data_array = <?php echo json_encode($data); ?>;
name_array = [];
count_array = [];
for(key in data_array){
  name_array.push(data_array[key][0]);
  count_array.push(data_array[key][1]);
  // alert(data_array[key][0] + "さんの番号は、" + data_array[key][1] + "です。") ;
}
console.log("ログを出力");
console.log(name_array);
console.log(count_array);

var ctx = document.getElementById("myBarChart");
  var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: name_array,
      datasets: [
        {
          label: 'チューターポイント',
          data: count_array,
          backgroundColor: "rgba(219,39,91,0.5)"
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: 'チューターポイントランキング'
      },
      scales: {
        yAxes: [{
          ticks: {
            suggestedMax: 20,
            suggestedMin: 0,
            stepSize: 5,
            callback: function(value, index, values){
              return  value +  ''
            }
          }
        }]
      },
    }
  });

詰まった点:
・どうやってphpからjsに値を渡すか(実際は配列だった。)
・渡した配列が、二重配列になっていたのに、気づかなかった
・配列なのに、

 datasets: [
        {
          label: 'チューターポイント',
          data: count_array,
          backgroundColor: "rgba(219,39,91,0.5)"
        }
      ]

のところで、data = [count_array]
としていて、表示がおかしくなっていた。
・データを加えるのがpushかappendかわからなかった

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?