Create several CSV files using MySQL and PHP

I've created a PHP script that is supposed to take an array and generate a CSV file for each element in the array. However, there seems to be an issue as it's not saving any files in the specified directory. Strangely, no errors are being returned either. Can anyone spot the problem?

$ids = json_decode($_POST['jsonarray']); // receiving array via ajax
$start = $_POST['start']; // receiving date via ajax
$end = $_POST['end']; // receiving date via ajax

$start_date = date('yyyy-mm-dd', strtotime($start)); // formatting dates for SQL
$end_date = date('yyyy-mm-dd', strtotime($end));

$toZip = array(); // preparing array for zip

if(is_array($ids)) {
    foreach ($ids as $key => $qr)
    {
        // Retrieving labels first
        // Preparing the first line of the .CSV file
        $tb = $qr . '_labels';
        $sql = $user_pdo->query("SELECT * FROM $tb");
        $head_array = array('Log ID', 'Timestamp');
        while ($row = $sql->fetch(PDO::FETCH_ASSOC))
        {
            $head_array[] = $row['label'];
        }

        // Setting up for database looping
        $table = $qr . '_data';
        $results = $user_pdo->prepare("SELECT * FROM $table WHERE timestamp BETWEEN :start_date AND :end_date;");
        $results->bindParam(':start_date', $start_date, PDO::PARAM_STR);
        $results->bindParam(':end_date', $$end_date, PDO::PARAM_STR);
        $results->execute();

        // Determining filename and destination directory
        $filename = "temp/db_user_export_".time().".csv";

        // Creating the file
        $handle = fopen($filename, 'w+');

        // Writing column titles
        fputcsv($handle, $head_array);

        // Writing user records to the file
        foreach($results as $row)
        {
            $rows = $row->rowCount();
            $insert_array = array();
            for ($i=0; $i<=$rows; $i++)
            {
                $insert_array[] = $row[$i];
            }

            fputcsv($handle, $insert_array);
        }

        // Finalizing the file
        fclose($handle);

        $toZip[] = $filename;
    }
}

Example using var_dump($ids);

array(4) {
  [0]=>
  string(5) "t23ry"
  [1]=>
  string(5) "6us32"
  [2]=>
  string(5) "se43z"
  [3]=>
  string(5) "o00gq"
}

Answer №1

After extensive searching and testing, I managed to solve the issue I was facing with this function:

    foreach($results as $row)
    {
            // the number of rows is unknown
        $rows = count($row);
        $insert_array = array();
        for ($i=0; $i<=$rows; $i++)
        {
            // function logic here
            $insert_array[] = $row[$i];
        }

        fputcsv($handle, $insert_array);
    }

I identified a few reasons why it wasn't working:

  1. The line $rows = $row->rowCount(); should be changed to $rows = count($row);
  2. The number of elements in the $row array exceeded my expectations, which led me to modify my select statement to
    $results = $user_pdo->query("SELECT * FROM $table WHERE timestamp >= '$start' AND timestamp <= '$end'", PDO::FETCH_NUM);
    . This allowed me to retrieve rows in numeric order, enabling proper handling of $row[$i] -> array.
  3. I also transitioned from using a prepared statement to a regular query, and adjusted the formatting of start and end date variables.

It took some time, but I'm pleased that everything is now functioning correctly. Huge thanks to everyone who offered their support!

Answer №2

fputcsv function only outputs one line at a time. Here is how you can simplify the code:

        for ($i=0; $i<=$rows; $i++)
        {
            // your function logic here
            fputcsv($handle, $row[$i]);
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize custom {tags} for replacing strings in a CSS file using str_replace in PHP

My code consists of a script that updates a CSS file based on user input from an html form. The script executes a str_replace function, scanning the CSS file for specific "tags". For example: html,body { background: {bgcolor} url(../images/bg.jpg) re ...

What is the method for appending an element to an array in PHP?

I've been trying to work with this code snippet, but it's not functioning as expected. Regardless of how many items I add, it only shows one item in the array. Could someone please point out where I might be making a mistake? session_start(); ...

What is the process for submitting a form with the GET method to a third-party URL using jQuery and Ajax?

For my WordPress project, I am looking to submit a form using AJAX with the GET method. I have tried two methods but they are not working for me. There seems to be an issue in my code. Method-1 Using $.get $.get( "http://**.70.120.**/web/sms.aspx", { fu ...

Pandas in an endless loop?

How can I identify and resolve a potential infinite loop in my code? This is the code snippet in question: new_exit_date, new_exit_price = [] , [] high_price_series = df_prices.High['GTT'] entry_date = df_entry.loc['GTT','entry_da ...

Completing two tasks with a single form submission and a single button press

I'm currently working on a script that inserts data into a database using a form. I'm trying to figure out how to trigger another action in a different section after the insertion. Any insights or tips would be greatly appreciated! ...

PHP - converting an array to JSON format and returning it

Let me start by mentioning that I have explored various Stack Overflow threads on this topic, yet I still find myself perplexed. Within my PHP code, I retrieve data from my database and attempt to store it in an array like so: $arrayResult = array(); ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

Failed to save information in JSON format

I'm currently facing an issue with JSON while trying to implement a register and login feature. The data fails to be stored as intended. Here is the JSON response I am receiving in the log: 02-24 08:24:47.878: E/JSON(2017): {"tag":"register","success ...

Is proc_open() and passthru() required for Laravel to function properly?

Having issues installing laravel on a shared hosting at KVC webhost. Getting a blank page. Checked the log and it seems like proc_open() and passthru() aren't enabled on my server, which is causing errors. Reached out to my webhosting for help but the ...

Executing a form_open in CodeIgniter triggers a controller function passing an argument

Is it possible for something like this to happen? The standard syntax for form is: <?php echo form_open('controller_name/function_name');?> However, I have reached a point where I need to create a form controller function with an argumen ...

Rebuilding associative arrays using PHP

I'm attempting to reconstruct this array using a foreach loop : Array ( [0] => Array ( [ID] => 0 [NAME] => 400 [QUANTITY] => 12 ) [1] => Array ( [ID] => ...

Creating a new form upon clicking

By clicking the "Add New Job" link, a new form with three fields will appear. This is the primary form: <h2>JOB EXPERIENCE 1</h2> <div class="job-content"> <input type="text" value="Company" name="company" /> <input type="te ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info->stock ...

There seems to be an issue with the file upload process

I'm attempting to upload an image using the following code: $sourcePath = $_FILES['file']['tmp_name']; $targetPath = "upload/".$_FILES['file']['name']; move_uploaded_file($sourcePath, $targetPath); However, I ...

How to easily include a CMS page in multiple stores using Magento

I have set up multiple stores on my website. Let's say the second store is called Test. I've included the index.php file in the Test store using the following code: $mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER[&ap ...

Can data be transferred between browsers, such as from Google Chrome to Mozilla Firefox?

I have a dilemma with two separate pages—one for Admin and the other for User. The Admin page is named index.html <!DOCTYPE html> <html lang="en"> <head> <style> * { padding: 0; ...

Do you have any advice or tricks for quickly refactoring PHP code?

Currently, our in-house newsletter system is essentially PHPlist with a customized company logo. I've been tasked with enhancing the system with new features, but the PHPlist codebase is massive and difficult to work with. My plan is to break it down ...

Leveraging the power of PHP variables within jQuery code

Wondering how to incorporate a PHP value into jQuery? My approach involves retrieving the VAT rate from the database using PHP and storing it in $vatrate: $sqlv = <<<SQL SELECT * FROM `vatrate` WHERE id='1' SQL; if(!$resultv = $db-&g ...

Output the chosen item quantity in the WooCommerce cart

Is there a way to showcase the quantity of added products in the cart on the single product page as a text image? Here is what I'm currently using in functions.php, but I need to include the quantity number within: add_action('woocommerce_before ...

Unable to obtain the Twilio "call recording" URL

Currently, I am working on an online campaign management system that utilizes Twilio. Each campaign in the system will have a unique Twilio number and target number. When a call is made to a specific Twilio number assigned to a campaign, it will be forward ...