I am trying create a bar chart for the data in mysql using php. I use bootstrap template to create application. I have predefined barchart with static data. I wanna add the data from the database. I tried my best but could not find solution as I am beginner in Javascript. Please guide me to add data dynamically. The Script is below:
// Bar chart var ctx = document.getElementById("mybarChart"); var mybarChart = new Chart(ctx, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: '# of Votes', backgroundColor: "#26B99A", data: [10, 20, 30, 40, 20, 10, 40] }, { label: '# of Votes', backgroundColor: "#03586A", data: [41, 56, 25, 48, 72, 34, 12] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });
<div class="x_content"> <canvas id="mybarChart"></canvas> </div>
If I understand the environment, you have php-produced webpages. If so I would:
<script> </script>
tags and also wrap it in a JS Function which you'll call later in the page Inside your JS code, after datasets, write a php loop as this:
// Bar chart var ctx = document.getElementById("mybarChart"); var mybarChart = new Chart(ctx, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ <?php if (count($arrayOfData) > 0){ echo "label: '# of Votes',"; echo "backgroundColor: '#26B99A',"; echo "data: ["; $firstValue = true; foreach ($arrayOfData as $dataValue) { if ( ! $firstValue ) { echo ", ".$dataValue; } else { $firstValue = false; } echo $dataValue; } echo "]"; } else { //Decide what to do if you don't have data } ?> }] }'
Write the rest of the HTML/PHP page.
Note that if you want more than 1 bar in your graph you have to also cycle through different data sets, not only through one as I showed above for simplicity.
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.