I am creating a graph that should display data out of a database for each sensor that is in there. I had success when i set it to only 1 sensor but when I am trying to display a chart for each sensor in my database, there is no line showing.
I am using the following code:
// select all sensors in db
$sql = "SELECT * FROM sensoren";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// data of each row
while($row = $result->fetch_assoc()) {
$sensor = $row['sensor_id'];
echo "<div id='sensor-$sensor' class='sensoren'>";
echo "<div class='one-third'>";
echo "<center><h4>Sensor</h4></center>";
echo "<center><h4>$sensor</h4></center>";
echo "</div>";
echo "<div class='two-third'>";
/* Database settings for selecting of values that the sensor send to db */
$host = 'localhost';
$user = 'casbek1q_system';
$pass = 'JUITGhJ>NKIL^';
$db = 'casbek1q_system';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
$data1 = '';
$data2 = '';
// select data from each sensor in db
$sql2 = "SELECT * FROM `metingen` WHERE sensorid = '$sensor' ORDER BY id ASC LIMIT 10 ";
$result2 = mysqli_query($mysqli, $sql2);
// setting them in array
while ($row2 = mysqli_fetch_array($result2)) {
$data1 = $data1 . '"'. $row2['waarde'].'",';
$data2 = $data2 . '"'. $row2['timestamp'].'",';
}
// removing last comma
$data1 = trim($data1,",");
$data2 = trim($data2,",");
?>
<div class="container">
<h4>Laatste metingen van Sensor <?php echo $sensor ?></h4>
<canvas id="chart<?php echo $sensor;?>" style="width: 100%; height: 100%; background: #222; border: 1px solid #555652;"></canvas> <!-- giving each chart a unique ID -->
<!-- stuk script van chart.js om de grafiek te maken -->
<script>
var ctx = document.getElementById(chart<?php echo $sensor;?>).getContext('2d');
var myChart = new Chart(ctx), {
type: 'line',
data: {
labels: [<?php echo $data2; ?>], // times from measurement
datasets:
[{
label: 'Sensor <?php echo $sensor;?>', // give a name to line
data: [<?php echo $data1; ?>], // display measurements
backgroundColor: 'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {scales:{yAxes: [{beginAtZero: false}], xAxes: [{autoskip: true, maxTicketsLimit: 20}]}},
tooltips:{mode: 'index'},
legend:{display: true, position: 'top', labels: {fontColor: 'rgb(255,255,255)', fontSize: 16}}
}
});
</script>
<?php
echo "</div>";
echo "</div>";
echo "</div>";
} // end while loop, go to next sensor
}
There should be a line in each graph, since i have 2 sensors in my database and multiple measurements for each sensor.
I got this problem when i tried to make a unique chart for each sensor, because documentGetElementById needed an unique id for each table.