What are some best practices for exporting data from multiple MySQL tables to a CSV file using PHP?

When exporting data from multiple MySQL tables to a CSV file using PHP, it is best to fetch the data from each table separately and then combine it before writing it to the CSV file. This can be achieved by querying each table individually and then merging the results into a single array before exporting it to a CSV file.

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

// Query data from table1
$query1 = "SELECT * FROM table1";
$result1 = mysqli_query($connection, $query1);
$data1 = mysqli_fetch_all($result1, MYSQLI_ASSOC);

// Query data from table2
$query2 = "SELECT * FROM table2";
$result2 = mysqli_query($connection, $query2);
$data2 = mysqli_fetch_all($result2, MYSQLI_ASSOC);

// Merge data from both tables
$combinedData = array_merge($data1, $data2);

// Open a file for writing
$csvFile = fopen('export.csv', 'w');

// Write data to CSV file
foreach ($combinedData as $row) {
    fputcsv($csvFile, $row);
}

// Close the file
fclose($csvFile);

// Close MySQL connection
mysqli_close($connection);
?>