What are best practices for including field delimiters and escaping characters when exporting data from a database using PHP?
When exporting data from a database using PHP, it is important to include field delimiters around each field value to distinguish them and to escape any special characters that may cause issues. This can prevent data corruption or errors when importing the data into another system. One common approach is to use CSV (Comma-Separated Values) format with double quotes as delimiters and to escape special characters like commas or double quotes within the fields.
// Query to fetch data from the database
$query = "SELECT * FROM table_name";
// Execute the query
$result = mysqli_query($connection, $query);
// Open a file for writing
$file = fopen('exported_data.csv', 'w');
// Loop through the results and write to the file in CSV format
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($file, $row);
}
// Close the file
fclose($file);