-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'];
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
BTR383434
  • 3
  • 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 – RiggsFolly Mar 28 '21 at 17:37
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[this happens](https://media.giphy.com/media/kg9t6wEQKV7u8/giphy.gif)** 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](http://php.net/manual/en/book.pdo.php) – RiggsFolly Mar 28 '21 at 17:39
  • Perhaps something like https://stackoverflow.com/questions/16391528/query-mysql-and-export-data-as-csv-in-php might help. – Nigel Ren Mar 28 '21 at 17:56

1 Answers1

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);