How can PHP be used to retrieve data from a MySQL database for use in a 3D.js program?

To retrieve data from a MySQL database for use in a 3D.js program, you can use PHP to establish a connection to the database, query the data, and then encode it into a JSON format that can be easily consumed by the 3D.js program. The JSON data can then be passed to the frontend where it can be used to render the 3D visualization.

<?php
// Establish connection to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query data from MySQL database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

$data = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Encode data into JSON format
$json_data = json_encode($data);

// Close connection
$conn->close();

// Pass JSON data to frontend
echo $json_data;
?>