简体   繁体   中英

PHP - Oracle query CSV creation, return results on same row

First of all, I apologise if the question I ask here is stupid, I have tried to find the answer online but I can't seem to put the search term in a short amount of words (that manages to answer my question). Secondly, I know that the answer to my question is very simple, but I am fairly new to PHP/Scripting and have been stumped for hours on this trying to find a solution.

I have a PHP script which queries an Oracle database, outputs to a CSV file then emails the file to me. This is great except I want it all the results for the query to output to a single row.

I want to set up an automation which runs multiple queries (all with around 5-10 rows each) to output to a CSV file. An extract of the php file is as below:

$csvLength = fputcsv($tmp, array(
    'Code',
    'count(*)'
));

while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC))
{
    $csvLength += fputcsv($tmp, array(
        $row['Code'],
        $row['COUNT(*)']
    ));
}

rewind($tmp);
$csvContent = fread($tmp, $csvLength);
fclose($tmp);

This will write a CSV file with the output something like this:

Code,count(*)
APPLE,201
ORANGE,504
BANANA,864

What I want is for the output to go something like this:

Code,count(*),Code,count(*),Code,count(*)
APPLE,201,ORANGE,504,BANANA,864

(The top row does not necessarily need to output more than one rep)

I can then add on to the php script to include more queries so the created csv file will end up like this:

Run blah.php from dates 21/11/2011 to 27/11/2011...
Code,count(*),Code,count(*),Code,count(*)
APPLE,201,ORANGE,504,BANANA,864

Reason,count(*),Reason,count(*),Reason,count(*)
Rotten,10,Bruised,42,Fermented,67

Region,count(*),Region,count(*),Region,count(*)
Oddtown,503,Newtown,204,Averagetown,631

Thanks in advance for anyone that can answer my question. Again I can imagine the answer is probably very simple, but anything I try seems to give me errors and I can't seem to find the answer online anywhere.

I'd put my results in an array like so:

$arr = array('Apple', '201', 'Orange', 504);

Then I'd use fprintf and implode to print them in a row:

if (!($fp = fopen('file.txt', 'w'))) {
   exit;
}
fprintf($fp, "%s\n",implode(",", $arr));

This will output

Apple,201,Orange,504

For the column names all you have to do is get the number of results and print them that many times. For example if there were 5 results I'd do this:

fprintf($fp, "%s\\n", implode( ",", array_fill( 0, 5, "Code,count(*)" ) ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM