I am using the following sample code to export a query to a csv file:

<?php

// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=mydatabase", 'myuser', 'mypassword');
$sql = "SELECT username, email FROM users ORDER BY username";
$results = $conn->query($sql);

// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
$filename = "/tmp/db_user_export_".time().".csv";

// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'w+');

// Write the spreadsheet column titles / labels
fputcsv($handle, array('Username','Email'));

// Write all the user records to the spreadsheet
foreach($results as $row)
{
    fputcsv($handle, array($row['username'], $row['email']));
}

// Finish writing the file
fclose($handle);

?>

This outouts the results to each rows as follows:

Row One Results
Row Two Results
Row Three Results

and I need it to be in the following format:

`Row One Results Row Two Results Row Three Results

I need it to display three rows of data in a single row and then start a new line at the end of every third row. This is so I can export the records into another piece of software.

How can I do this in the export?

add a counter
when counter reaches 3 print a new line

Member Avatar for iamthwee

You could also use phpexcel which is more accurate if you need to open it in excel.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.