Chart.JS PHP Embedded

Here is a silly example to use Chart.JS . However, we are using advantages of PHP. I personally do not recommend to use that way in production. Maybe the second way?

We have a database with 3 columns.

CREATE TABLE "data" (
	"id"	INTEGER PRIMARY KEY AUTOINCREMENT,
	"temperature"	INTEGER,
	"day"	INTEGER
)

Embedded PHP Code

<!DOCTYPE html>
<html>
<head>
<title>Chart.js PHP Example</title>
</head>

<body>
<canvas id="myChart" width="25" height="10"></canvas>

<?php
$db = new SQLite3('chart.db');
$result = $db->query('SELECT * FROM data');
?>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [
        <?php 
        while ($row = $result->fetchArray()) {
        echo "'";
        echo $row['day'];
        echo "',";
        } ?>
        ],
        datasets: [{
            label: 'Temperature',
            data: [
            <?php
            while($row = $result->fetchArray()) {    
            echo "'";
            echo $row['temperature'];
            echo "',";
            }
            ?>
                ],
            lineTension: 0.5,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'        
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: false
                }
            }]
        }
    }
});
</script>

</body>

</html> 

Second way. Smarter Maybe???

 <!DOCTYPE html>
<html>
<head>
<title>Chart.js PHP Example</title>
</head>

<body>
<canvas id="myChart" width="25" height="10"></canvas>

<?php
$db = new SQLite3('chart.db');
$result = $db->query('SELECT * FROM data');
?>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>

var labels1 = new Array();  
var data1 = new Array();
<?php while ($row = $result->fetchArray()) { ?>
labels1.push(<?php echo $row['day']; ?>);
data1.push(<?php echo $row['temperature']; ?>);
<?php } ?>

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: labels1,
        datasets: [{
            label: 'Temperature',
            data: data1,
            lineTension: 0.5,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'        
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: false
                }
            }]
        }
    }
});
</script>

</body>

</html>