How can PHP be used to display data from a SQL database in a graph format?

To display data from a SQL database in a graph format using PHP, you can use a library like Chart.js or Google Charts. First, retrieve the data from the database using SQL queries in PHP. Then, format the data in a way that can be easily used by the charting library to create the desired graph. Finally, use the library's functions to generate and display the graph on your webpage.

<?php
// Connect to the 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);
}

// Retrieve data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

$data = array();
while($row = $result->fetch_assoc()) {
    $data[] = $row['column_name'];
}

// Format the data for the chart library
$data_json = json_encode($data);

// Display the graph using Chart.js
echo "<canvas id='myChart'></canvas>";
echo "<script src='https://cdn.jsdelivr.net/npm/chart.js'></script>";
echo "<script>";
echo "var data = " . $data_json . ";";
echo "var ctx = document.getElementById('myChart').getContext('2d');";
echo "var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Label1', 'Label2', 'Label3'], datasets: [{ label: 'Data', data: data }] } });";
echo "</script>";

$conn->close();
?>