-2

I am trying to create a csv file out of this and save it to a file in my directory. How would you accomplish this? Thanks.

$sql = mysql_query("SELECT code, count FROM products WHERE active = '1' ORDER BY code Asc") or die(mysql_error());

while ($row = mysql_fetch_array($sql)) {
    $code = $row['code'];
    $quantity = $row['quantity'];
}
3
  • 1
    1) open a file fopen(), in whatever location on disk you like (or have the privileges for) 2) look up fputcsv() 3) close the file Commented Mar 28, 2021 at 17:37
  • Every time you use the mysql_ database extension in new code this happens it is deprecated and has been for years and is gone for ever in PHP7.0+. If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements. Start here Commented Mar 28, 2021 at 17:39
  • Perhaps something like stackoverflow.com/questions/16391528/… might help. Commented Mar 28, 2021 at 17:56

1 Answer 1

0

// open the file for writing

$file = fopen('dir path/filename_to_be_saved.csv', 'w');

 

// save the column headers

fputcsv($file, array('code', ‘quantity'));

 

// save row data

while ($row = mysql_fetch_array($sql)) { $code = $row['code']; $quantity = $row['quantity']; $csv_row = array($code, $quantity);
fputcsv($file, $csv_row);
}

// Close the file

fclose($file);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.