In what scenarios does the PHP script fail to generate a CSV file when exporting a MySQL table?

The PHP script may fail to generate a CSV file when exporting a MySQL table if there are errors in the query, the file path is incorrect, or the file permissions are not set correctly. To solve this, ensure that the query is correct, the file path is valid, and the file permissions allow the script to write to the directory.

<?php
// Connect to MySQL database
$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);
}

// Query to select data from MySQL table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Path to save CSV file
$filepath = 'path/to/save/file.csv';

// Open file for writing
$file = fopen($filepath, 'w');

// Check if file opened successfully
if ($file === false) {
    die("Error opening file");
}

// Write data to CSV file
while ($row = $result->fetch_assoc()) {
    fputcsv($file, $row);
}

// Close file and database connection
fclose($file);
$conn->close();

echo "CSV file generated successfully";
?>