How can MySQL data be retrieved and displayed in JavaScript for use in a chart?
To retrieve MySQL data and display it in JavaScript for use in a chart, you can use AJAX to make a request to a PHP script that fetches the data from the database and returns it in JSON format. The JavaScript code can then parse the JSON data and use it to populate the chart.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data from MySQL
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Close MySQL connection
$conn->close();
// Return data in JSON format
header('Content-Type: application/json');
echo json_encode($data);
?>