What is the best way to convert a MySQL table into a CSV file and send it via email using PHP without saving the file?
To convert a MySQL table into a CSV file and send it via email using PHP without saving the file, you can use PHP's built-in functions to fetch the data from the MySQL table, format it as CSV, and then send it as an attachment in an email. This can be achieved by using PHP's MySQLi or PDO extension to retrieve the data, fputcsv() function to format it as CSV, and PHPMailer library to send the email with the CSV file as an attachment.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Fetch data from MySQL table
$result = $mysqli->query("SELECT * FROM table_name");
// Create CSV file in memory
$csv_data = '';
while ($row = $result->fetch_assoc()) {
$csv_data .= implode(',', $row) . "\n";
}
// Send CSV file via email
require 'PHPMailer/PHPMailer.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@example.com', 'Recipient Name');
$mail->Subject = 'MySQL Table Data CSV';
$mail->Body = 'Please find attached the MySQL table data in CSV format.';
$mail->addStringAttachment($csv_data, 'mysql_table_data.csv', 'base64', 'text/csv');
// Send email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error sending email: ' . $mail->ErrorInfo;
}