0

I have an array whose structure is like $data = array{0=>'abc',1=>xyz,2=>tqs}

Now I need to write these values into a csv file. I need to display every value in 1st column and with everytime new row on new insert along with previous value already available.

Below is the code I am using but everytime I execute it I get the last value in the file:

for ($c=0; $c < $num; $c++) {
      echo $data[$c];
   echo  $query = "select prod_sku,prod_name 
    from
      tbl_product
    where 
     prod_sku = '".$data[$c]."'";
     $result = mysql_query($query);
     $row = mysql_fetch_array($result);
     if(empty($row)){
     print_r($row);
     echo 'test';
     $fp = fopen("file.csv", "w");
     print_r($data[0]);

      fputcsv($fp, $data[0]);
      fclose($fp);


  } 

How can i achieve this using PHP?

2 Answers 2

5

The problem is that you are doing fopen inside the for loop, so every time the loop runs, your file gets re-written. Move the fopen and fclose outside of the loop and it will work. Like this;

$fp = fopen("file.csv", "w");
for ($c=0; $c < $num; $c++)
{
     $query = "select prod_sku,prod_name from tbl_product where prod_sku = '".$data[$c]."'";
     $result = mysql_query($query);
     $row = mysql_fetch_array($result);

     fputcsv($fp, $data);
} 
fclose($fp);
Sign up to request clarification or add additional context in comments.

Comments

0

If you use MySQL you could use SELECT ... INTO OUTFILE:

SELECT prod_sku, prod_name
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM tbl_product
WHERE 1

http://dev.mysql.com/doc/refman/5.0/en/select.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.