What are some alternative methods for creating JavaScript arrays from MySQL data in PHP without encountering issues with variable incrementation?

When creating JavaScript arrays from MySQL data in PHP, using variable incrementation to populate the array can lead to issues such as missing or duplicated data. To avoid this problem, you can use the `json_encode` function in PHP to directly convert the MySQL data into a JSON array without the need for manual variable incrementation.

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

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

// Create array from MySQL data
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// Convert array to JSON
$json_data = json_encode($data);

// Output JSON data
echo "var jsonData = " . $json_data . ";";
?>