javascript - JS Chart is displayed only once in php loop

I have a script where many database entries should be displayed one below the other in a box. All PHP variables work perfectly in the PHP loop except the JavaScript code is only displayed once in the first box. In the other boxes I see only the empty div class.
How can I make each box show a different chart with its value, not only one? Here is the rough code:
index.php:
<!--Other code-->
<?php
$query = "SELECT * FROM accounts WHERE user ='$user' ORDER BY date DESC";
$results = $db->query($query);
while($row = mysqli_fetch_array($results)){
?>
<div class="accounts">
<p>Name: <?php echo $row['name']; ?></p>
<img class="icon" src="/icons/profile.png">
<div class="chart-box">
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<div id="my-chart" class="ct-chart ct-perfect-fourth"></div>
</div>
</div>
<script>
var data = {
series: [
{
data: [<?=$row['value1']?>, <?=$row['value2']?>, <?=$row['value3']?>, <?=$row['value4']?>]
}
]
};
var options = {
axisX: {
}
};
var responsiveOptions = [
['screen and (min-width: 641px) and (max-width: 1024px)', {
showPoint: false,
axisX: {
labelInterpolationFnc: function(value) {
return 'Week ' + value;
}
}
}],
['screen and (max-width: 640px)', {
showLine: false,
axisX: {
labelInterpolationFnc: function(value) {
return 'W' + value;
}
}
}]
];
new Chartist.Line('#my-chart', data, options, responsiveOptions);
</script>
<?php
}
?>
<!--Other code-->
I have 4 users in the database, but the chart is only displayed for the first user in the first box.
Thanks for help!
Answer
Solution:
This is because, the you are targeting your each chart by the same id i.e.,id="my-chart"
,
and Id is unique for each tag. If you want to render chart for each user, try targeting it with class instead of id or you can can generate Unique id for each user, e.g,
<div id="my-chart-<?php echo $row['id']; ?>" class="ct-chart ct-perfect-fourth"></div>
and then target them by unique ids.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.