【问题标题】:draw a pie chart using php and mysql使用php和mysql绘制饼图
【发布时间】:2023-03-20 23:50:02
【问题描述】:

我正在尝试使用 PHP 和 MySQL 绘制饼图,但我什么也没看到,任何错误只是一个空白页,我不知道问题到底出在哪里,我的查询是正确的。任何帮助,任何建议!谢谢你。这是我正在使用的代码:

<?php
    $dsn='mysql:host=localhost;dbname=tp3_php';
    $user='root';
    $pass='';
    try {
      $bdd = new PDO($dsn,$user,$pass);
    } catch (Exception $e) {
      die('Erreur : ' . $e->getMessage());
    }    
    $sql="
    SELECT Nom_matiere
         , COUNT(ID_etudiant)  
      FROM note
         , matiere 
     WHERE note>=12 
       and matiere.Num_matiere = note.Num_matiere 
     GROUP 
        BY note.Num_matiere
    ";
            $sth = $bdd->query($sql);
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Nom_matiere', 'taux de reussis'],
          <?php

              while ($result=$sth->fetchAll()) 
              {

      echo "['".$results['Nom_matiere']."',".$results['COUNT(ID_etudiant)']."],";
              }

          ?>

        ]);

        var options = {
          title: 'Taux de réussite des étudiants par module'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

【问题讨论】:

  • 给计数起别名
  • @strawberry 你的意思是重命名 count(ID_etudiant) ??
  • @strawberry 我做了$sql="SELECT Nom_matiere, COUNT(ID_etudiant) as ID FROM note,matiere WHERE note&gt;=12 and matiere.Num_matiere=note.Num_matiere GROUP BY note.Num_matiere"; 然后我改变了echo "['".$results['Nom_matiere']."',".$results['COUNT(ID_etudiant)']."],"; echo "['".$results['Nom_matiere']."',".$results['ID']."],"; 但没有任何改变!!
  • 我觉得这几乎难以辨认:-(
  • 我告诉过你我重命名 count(ID_etudiant) , count(ID_etudiant) 为 ID,就像你告诉我的那样,但我得到了同样的错误@strawberry

标签: php mysql pie-chart


【解决方案1】:

它对我有用:我添加了这一行 $result=$sth-&gt;fetchAll(); 并添加了一个循环 foreach,代码将是这样的:

['Nom_matiere', 'taux de reussis'],
          <?php
              $result=$sth->fetchAll();
            foreach ($result as $row) { 
              echo "['".$row['Nom_matiere']."',".$row['COUNT(ID_etudiant)']."],";
            }

          ?>

【讨论】:

  • 酷。 FWIW,我觉得这更容易阅读:echo "['{$row['Nom_matiere']}',{$row['id']}],";
  • 另外,使用与所选列不同的列进行 GROUP BY 是没有意义的 - Nom_matiere &lt;&gt; note.num_matiere
  • 并且始终使用显式 JOIN 语法编写您的 JOIN。我们在 1992 年停止使用逗号连接。并限定所有列名!
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多