How can JSON encoding be effectively used in PHP to pass data from a MySQL query to JavaScript for dynamic content on a webpage?

To pass data from a MySQL query to JavaScript for dynamic content on a webpage, you can use JSON encoding in PHP. This involves fetching the data from the MySQL database, encoding it as JSON, and then passing it to JavaScript for manipulation and display on the webpage. This approach ensures that the data is transferred in a structured format that can be easily parsed and used by JavaScript.

<?php
// Connect to MySQL database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');

// Fetch data from MySQL query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Fetch data as an associative array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Encode data as JSON
$json_data = json_encode($data);

// Pass JSON data to JavaScript
echo "<script>var jsonData = $json_data;</script>";
?>