1

I think I used fputcsv correctly.My database table contains two columns with dates and numbers in both columns. I use an oracle database and a windows 2008 server.

//Connexion BDD Oracle
$connect = odbc_connect("oraclesrc", "xe", "sec123");

$query = "select * from timedata";

$result = odbc_exec($connect, $query);

$numOF = 0;
while(odbc_fetch_row($result)) {
    $emp = odbc_result($result, 1);
    $time = odbc_result($result, 2);
    $numOF++;
    echo $emp; 
    echo $time;     
}

$fp = fopen('testfile.csv', 'w');
foreach ($row as $result) {
    fputcsv($fp, $result);
}
fclose($fp);

odbc_close($connect);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Theo27
  • 385
  • 4
  • 17
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](http://www.php-fig.org/psr/psr-2/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Jan 14 '20 at 16:11
  • You wrote a WHILE Loop to process the result set, but you didnt write the csv file in there ?? – RiggsFolly Jan 14 '20 at 16:13
  • I have to put my foreach in my while? – Theo27 Jan 14 '20 at 16:14
  • Does the while loop produce any output? – RiggsFolly Jan 14 '20 at 16:15
  • `$row` does not seem to exists before you attempt to foreach loop over it ?? – RiggsFolly Jan 14 '20 at 16:15
  • No it doesn't exist, what should I put in its place? – Theo27 Jan 14 '20 at 16:17
  • Overall it might be more efficient to use the native PHP OCI8 extension instead of ODBC. Or use SQL*Plus :) https://blogs.oracle.com/opal/fast-generation-of-csv-and-json-from-oracle-database – Christopher Jones Jan 15 '20 at 22:29

1 Answers1

2

The while loop fetches the result rows one at a time. If you change to use odbc_fetch_array($result) you will get an Assoc array exactly as fputcsv() want to see it.

//Connexion BDD Oracle
$connect = odbc_connect("oraclesrc", "xe", "sec123");
$query = "select * from timedata";
$result = odbc_exec($connect, $query);

$fp = fopen('testfile.csv', 'w');

while($row = odbc_fetch_array($result)) {
    fputcsv($fp, $row);
}
fclose($fp);
odbc_close($connect);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149