Is using mysqli_fetch_assoc() a better approach than mysqli_fetch_row() when creating a CSV file in PHP?
When creating a CSV file in PHP, using mysqli_fetch_assoc() is generally a better approach than mysqli_fetch_row(). This is because mysqli_fetch_assoc() returns an associative array with column names as keys, making it easier to map the data to CSV headers. On the other hand, mysqli_fetch_row() returns a numerical array, which requires additional logic to map the data correctly.
<?php
// Connect to database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch data
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
// Create CSV file
$fp = fopen('output.csv', 'w');
// Write headers
$headers = array();
while ($fieldinfo = mysqli_fetch_field($result)) {
$headers[] = $fieldinfo->name;
}
fputcsv($fp, $headers);
// Write data
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($fp, $row);
}
// Close file and database connection
fclose($fp);
mysqli_close($conn);
?>
Related Questions
- What are the best practices for handling client requests to automatically resize images without manual intervention, such as using Photoshop?
- How can developers troubleshoot and debug issues with array_multisort in PHP when the desired sorting results are not achieved, as seen in the initial problem description?
- What is the significance of using the strtotime function in PHP for date manipulation?