How can PHP be used to save SQL query results into multiple CSV files based on specific values in a row?
To save SQL query results into multiple CSV files based on specific values in a row, you can use PHP to fetch the data from the database, iterate through the results, and conditionally write each row to different CSV files based on the specific values. You can achieve this by using PHP's file handling functions to create and write to multiple CSV files dynamically.
<?php
// Connect to the 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);
}
// Execute SQL query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Create CSV files based on specific values in a row
while ($row = $result->fetch_assoc()) {
$value = $row['specific_column'];
$filename = "output_" . $value . ".csv";
$file = fopen($filename, 'a');
fputcsv($file, $row);
fclose($file);
}
// Close database connection
$conn->close();
?>
Related questions
-
CSS external file organization
-
PHP SQL queries SELECT *
-
PHP imagefilledarc image