Using chart.js I want to create a graph of a given stock price. The labels and data are fetched using the data from $select_query. Here I create a dynamic function that gets the ticker name from the URL: https://signal-invest.com/tick/?ticker=LOW
$select_query = $con->prepare("SELECT Date_buy, Name_buy, Price_buy FROM daily_buy_orders WHERE Name_buy = ?");
$select_query->bind_param('s', $ticker); // 's' specifies the variable type => 'string'
$select_query->execute();
I tried to loop through the rows using the while loop but failed.
<canvas id="myChart" style="border: 1px solid black; margin: 25px 25px" height="300"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
labels: [<?php
$get_dates = $select_query->get_result();
while ($rows = mysqli_fetch_assoc($get_dates)) {
$dates = $rows["Date_buy"];
echo ''.$dates.'';
}
?>],
datasets: [{
label: '# of Votes',
//data: [12, 19, 3, 5, 2, 3],
data: [<?php
$get_prices = $select_query->get_result();
while ($rowss = mysqli_fetch_assoc($get_prices)) {
$prices = $rowss["Price_buy"];
echo ''.$prices.'';
}
?>],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(75, 192, 192)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
Above code messes with my table below. When creating the tables the while loop actually works. I tried to use the same thinking when doing the while loops for the labels and data in chartjs, didn't work though.
<table style="width:50%" border="solid">
<tr>
<th>Name</th>
<th>Price</th>
<th>Date of signal</th>
</tr>
<?php
$result = $select_query->get_result();
while ($row = mysqli_fetch_assoc($result)) {
$name_buy = $row["Name_buy"];
$price_buy = $row["Price_buy"];
$date = $row["Date_buy"];
echo buy_table($name_buy, $price_buy, $date);
}
?>
</table>
json_encodeor also you can try withlabels:['<?php echo implode("','", $dates); ?>'],