简体   繁体   中英

Data for the Morris.js bar graph is from a php database loop

I have this PHP code:

$number = mysqli_num_rows(mysqli_query($db_conn, "Select * from barangay"));
for ($i=1; $i<=$number; $i++){
$chart_fetch=mysqli_query($db_conn, "Select * from health where BRGY_id=$i");
  $chart_data[$i] = "";
    while($chart=mysqli_fetch_array($chart_fetch)){
      $chart_data[$i] .= "{year:'".$chart["year"]."', pneumonia:".$chart["pneumonia"].", asthma:".$chart["asthma"].", tuberculosis:".$chart["tuberculosis"]."}, ";
    }
    $chart_data[$i] = substr($chart_data[$i], 0, -2);
}

and for the chart script:

<script>
        var max = <?php echo $number; ?>;
        for (i=1; i<=max; i++){
          Morris.Bar({
            element: 'chart'+i,
            data:[ <?php echo $chart_data[$i]; ?>],
            xkey:'year',
            ykeys:['pneumonia',  'asthma', 'tuberculosis'],
            labels:['Pneumonia', 'Asthma', 'Tuberculosis'], //label for the pop-up key
            hideHover:'auto',
            barColors: ['#036016', '#009f29', '#03440C']
          });
       }
      </script>

I can't seem to get the chart_data[$i] to keep on adding one value so that i could get the fetched data from the php script as I had stated above.

The output of my codes must look like this: For Barangay 1 For Barangay 2

Because I cannot create loop or concatenate the script variable i to the php code because of the client and server issue.

I already got the answer to my problem. All I have to do was just to insert the script inside the php code, and let php do the looping for me.

I should have known it sooner. :)

But anyway, here's the code to help others with cases such as this.

<?php 
        $number1 = mysqli_num_rows(mysqli_query($db_conn, "Select * from barangay"));
          for ($z=1; $z<=$number1; $z++){
            $z=$z;
            echo"<script>
              var i =1;
              var max= $number1;
                Morris.Bar({
                  element: chart$z,
                  data:[$chart_data[$z]],
                  xkey:'year',
                  ykeys:['pneumonia',  'asthma', 'tuberculosis'],
                  labels:['Pneumonia', 'Asthma', 'Tuberculosis'],
                  hideHover:'auto',
                  barColors: ['#036016', '#009f29', '#03440C']
                });
            </script>
            ";
          }
      ?>

And the output would be different bar graphs which are getting their data from the database. <3 Like this, (this is from a 67% zoom from my web browser so you could see 2 of my 7 graphs having different data fetched from the database): Bar Graph 1 and 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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