I am trying to display the population of each state in the US and show this in a bar chart. I am definetly a begineer at this so be kind :-) echo out of some of the data only one state is being shown
I seem to be able to connect to my database ok and echo out all the data but its not displaying correctly in the bar chart. It is just showing the last entry "Wyoming". Here is my code and help would be massively appreciated !!
<?php
include("conn.php");
$query = "SELECT * FROM usa_pop2";
$result = $conn->query($query);
if (!$result) {
echo $conn->error;
exit();
}
//print_r($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.2/helpers.esm.min.js" integrity="sha512-JC8H/YEABKWyV0Q/pgk3GfyrUCEiESg3ZM8DMdI8XD4zlwgtFyezG2dSenJ9pxAtJU2Bds6YNKYThXaLQrf9bw==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<title>Charts</title>
</head>
<body>
<?php
$states = "";
$p2018 = 0;
$p2019 = 0;
$p2020 = 0;
while ($row = $result->fetch_assoc()) {
$states = '"' . $row["state"] . '",';
$p2018 = '"' . $row["pop2018"] . '",';
$p2019 = '"' . $row["pop2019"] . '",';
$p2020 = '"' . $row["pop2020"] . '",';
echo "<p> $states - $p2018</p>";
///note to self go back take a look at this and then you might need to do do comma seperated for the data
}
?>
<div class="container">
<h2>my data</h2>
</div>
<div class="container">
<canvas id="myChart"></canvas>
</div>
<script>
let myChart = document.getElementById('myChart').getContext('2d');
// global options
//Chart.defaults.global.defaultFontFamily = 'Lato';
//Chart.defaults.global.defaultFontSize = 18;
//Chart.defaults.global.defaultFontcolor = '#777';
let popChart = new Chart(myChart, {
type: 'bar', //bar, horiz bar
data: {
labels: [<?php echo trim($states); ?>],
datasets: [{
label: 'Population',
data: [<?php echo trim($p2019); ?>],
backgroundColor: '#581845',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
//Add the tooltips
tooltips: {
callbacks: {
label: function(tooltipItem) {
return "€" + Number(tooltipItem.yLabel);
}
}
},
}
});
</script>
</body>
</html>