I'm trying to import readings from mySQL database, and place them on a ChartJS.
$query = mysqli_query($conn, "SELECT * FROM readings
ORDER BY readings_id DESC LIMIT 2");
$distance = array();
$timestamp = array();
while($row = mysqli_fetch_array($query)) {
$distance[] = $row['river_height'];
$time[] = $row['time_stamp'];
}
This is the query I'm using and the method I'm doing to store readings in an array.
However, when I try to place these in a bar chart for example, the 2 readings will act as one. I have the Javascript code as follows:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: [time],
datasets: [{data:[10, 20]}],
}
}
I've tried quite a lot of things, but can't figure it out. I'm new to this, so it doesn't help. Any advice or help would be appreciated.
CodePudding user response:
This is happening because your PHP is returning an array for the labels and then you put that array in another array. This tells chart.js that it has to be a multiline label as you can see. To get the behaviour you want you need to remove the array brackets at the labels field like so:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: time, // remove array brackets around time
datasets: [{data:[10, 20]}],
}
}
CodePudding user response:
Assuming you want time_stamp
as the X axis, and river_height
as the Y axis, change to :
PHP :
while($row = mysqli_fetch_array($query)) {
$data[] = [
'x' => $row['time_stamp'],
'y' => $row['river_height']
];
}
JavaScript :
var config = {
type: 'bar',
data: {
datasets: [{
data: <?= json_encode($data) ?>
}]
}
};