If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

SQL and .csv

Started by jacoblin, Dec 26, 2022, 04:33 AM

Previous topic - Next topic

jacoblinTopic starter

Greetings!

My task is to query a table in a database, select all fields from it, and save the rows of the table to a .csv file. I need to create a folder for storing the saved files.

Here are a few questions I have:

1. Where do I add the SELECT statement?
2. How do I insert table rows into a .csv file?
3. How do I put the .csv file into the appropriate folder?

Currently, I have a starting point in PHP, but I'm not sure if it's correct.

<?php
    $host 
'localhost'// Server address
    
$db_name 'database'// Database name
    
$user 'user'// Username
    
$password 'password'// Password
 
    // Create a connection to the database
    
$connection mysqli_connect($host$user$password$db_name);
 
    
// SQL query text that will be passed to the database
    
$query 'SELECT * FROM USERS';
 
    
// Execute a database query
    
$result mysqli_query($connection$query);

    
// Create an array to hold the data from the query result
    
$fields = [];

    
// Enter data from the database into the created array
    
foreach ($row $result->fetch_assoc()) {
        
$fields[] = $row;
    }

    
// Open a file pointer for writing to a .csv file
    
$fp fopen('path/to/folder/table.csv''w');

    
// Output the received data to the .csv file
    
foreach ($fields as $field) {
        
fputcsv($fp$field);
    }

    
// Close the file pointer and release the database connection
    
fclose($fp);
    
mysqli_close($connection);
?>

  •  

aliceria

You can export table data from a MySQL database into a .csv file using the SELECT statement with the INTO OUTFILE option. This can be achieved in one request, without using any PHP code.

Here's the basic structure of the SQL query:

SELECT * FROM USERS INTO OUTFILE '/path/to/file.csv'
The SELECT statement retrieves all data from the USERS table, while the INTO OUTFILE clause specifies the path where the .csv file should be saved. To use this feature, you need permission to write files on your MySQL server and make sure that the path specified in the query exists and that you have write permissions for it.

You can find more information about the SELECT statement options in the MySQL reference documentation.
  •  

RonaldVance

You've got it in the right spot, my friend! The $query variable contains the SQL query that will retrieve all the fields from the USERS table. However, I'd like to suggest a minor modification to make your code more robust: use prepared statements to prevent SQL injection attacks. Replace the $query variable with the following code:

$query = "SELECT * FROM USERS";
$stmt = mysqli_prepare($connection, $query);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

Now, let's discuss the process of inserting table rows into a.csv file. You're on the right track with the fputcsv() function, but there's a slight issue. The $fields array contains associative arrays, which won't work with fputcsv(). Instead, you need to extract the individual field values and pass them as an array to fputcsv(). Here's the corrected code:

foreach ($result as $row) {
    $csv_row = [];
    foreach ($row as $field => $value) {
        $csv_row[] = $value;
    }
    fputcsv($fp, $csv_row);
}

Moving on to the folder creation and file saving process. You're close, but you need to create the folder before attempting to write to it. Use the mkdir() function to create the folder, and then use the fopen() function to open the file in write mode:

$folder_path = 'path/to/folder';
if (!is_dir($folder_path)) {
    mkdir($folder_path, 0777, true);
}
$fp = fopen($folder_path. '/table.csv', 'w');

Finally, don't forget to close the file pointer and release the database connection using fclose() and mysqli_close() respectively.

Here's the revised code, incorporating the suggestions above:

<?php
    $host = 'localhost'; // Server address
    $db_name = 'database'; // Database name
    $user = 'user'; // Username
    $password = 'password'; // Password

    // Create a connection to the database
    $connection = mysqli_connect($host, $user, $password, $db_name);

    // SQL query text that will be passed to the database
    $query = "SELECT * FROM USERS";
    $stmt = mysqli_prepare($connection, $query);
    mysqli_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    // Create an array to hold the data from the query result
    $fields = [];

    // Enter data from the database into the created array
    foreach ($result as $row) {
        $csv_row = [];
        foreach ($row as $field => $value) {
            $csv_row[] = $value;
        }
        $fields[] = $csv_row;
    }

    // Create the folder and file
    $folder_path = 'path/to/folder';
    if (!is_dir($folder_path)) {
        mkdir($folder_path, 0777, true);
    }
    $fp = fopen($folder_path. '/table.csv', 'w');

    // Output the received data to the.csv file
    foreach ($fields as $field) {
        fputcsv($fp, $field);
    }

    // Close the file pointer and release the database connection
    fclose($fp);
    mysqli_close($connection);
?>

With these tweaks, you should be able to export your data to a.csv file in the desired folder.
  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...