What are some best practices for exporting data from a MySQL database to a Word document using PHP?
When exporting data from a MySQL database to a Word document using PHP, one common approach is to fetch the data from the database, format it as needed, and then use a library like PHPWord to generate the Word document. This can be achieved by first establishing a database connection, querying the data, and then creating a Word document with the fetched data.
<?php
require_once 'vendor/autoload.php'; // Include PHPWord library
// Create a new PHPWord object
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from MySQL database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Create a new section in the Word document
$section = $phpWord->addSection();
// Loop through the fetched data and add it to the Word document
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$section->addText($row['column1'] . ' - ' . $row['column2']);
}
} else {
echo "0 results";
}
// Save the Word document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('data_export.docx');
// Close the database connection
$conn->close();
?>
Keywords
Related Questions
- In what scenarios would using a database like SQLite be more beneficial than relying on sessions or cookies in PHP?
- What are the potential pitfalls of using the "zurück-Button" in the browser after logging out in PHP applications?
- What are some alternative solutions or approaches to verifying the existence of a link in PHP if direct methods are not available?