动态morris甜甜圈图表与php mysql

时间:2017-09-14 17:05:13

标签: php mysql morris.js

我正在尝试制作莫里斯甜甜圈图表,由于不明原因我得到了空白页面。我有两个单独的文件,Chart.php包含sql语句,然后是用于显示图表的邮件文件。

Chart.php代码

  try { $stmt = $db->prepare(" SELECT gender, count(*) as no_of_gender FROM 
 members GROUP BY gender ORDER BY memberID ASC ");
        $stmt->execute();
      }
  catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
      }

    $data = array();

   while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $array[] = array(
          'lable' => $row['gender'],
          'value' => $row['no_of_gender']
          );
      }

$data = json_encode($data);

这是我的javascript代码,用于接收$ data Chart.php

 <script type="text/javascript" language="javascript" >

      $(document).ready(function(){

         var donut_chart = Morris.Donut({
            url :"charts.php",
            element: 'chart',
            data: <?php echo $data; ?>
              });
          })

  </script>

1 个答案:

答案 0 :(得分:1)

在chart.php文件中,您正在编码一个空数组。

替换

$data = json_encode($data);

$data = json_encode($array);

确保您正确地将$ data从chart.php文件传递到javascript代码。

工作代码在

之下
<html>
<head>
    // if you have downloaded these files to your project, change the path to include them.
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
</head>
<body>

<?php
try { $stmt = $db->prepare(" SELECT gender, count(*) as no_of_gender FROM 
 members GROUP BY gender ORDER BY memberID ASC ");
        $stmt->execute();
      }
  catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
      }

    $data = array(); // define array

   while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[] = array(
          'lable' => $row['gender'],
          'value' => $row['no_of_gender']
          );  
      }

//print_r($data);  // to check the array data
$json_data = json_encode($data);  // convert to json array
 ?>
<div id="chart" style="height: 250px;"></div>

<script type="application/javascript">

    Morris.Donut({
      element: 'chart',  // div id
      data: <?php echo $json_data; ?>,
      xkey: 'lable',
      ykeys: ['value'],
      labels: ['Value']
  });

</script>


</body>
</html>