Insert new column into CSV export using PHP and MySQL

I am using the following code to generate a .csv file based on a MySQL query using PHP.  This works great except for I have to add a column called Country that is not found in the table.  How do I update this code to insert a column called Country for each record and insert USA as the data when inserting the data into the .csv?

<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$values = mysql_query("SELECT COLUMN1, COLUMN2, COLUMN3 FROM ".$table."");
$row = 0;
while ($rowr = mysql_fetch_assoc($values)) 
{
  if ($row == 0)
  {
    foreach($rowr as $name => $value)
    {
      $csv_output .= $name . "; ";
    }
    $csv_output .= "\n";
  }
  $row++;

  foreach($rowr as $name => $value)
  {
    $csv_output .= $value . "; ";
  }
  $csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

Open in new window

pda4meAsked:
Who is Participating?
 
mars-vieConnect With a Mentor Commented:
Try this -->

<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$values = mysql_query("SELECT COLUMN1, COLUMN2, COLUMN3 FROM ".$table."");
$row = 0;
while ($rowr = mysql_fetch_assoc($values))
{
  if ($row == 0)
  {
    foreach($rowr as $name => $value)
    {
      $csv_output .= $name . "; ";
    }
    $csv_output .= "Country". "; ";
    $csv_output .= "\n";
  }
  $row++;

  foreach($rowr as $name => $value)
  {
    $csv_output .= $value . "; ";
  }
  $csv_output .= "USA". "; ";
  $csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>


M@RS
0
 
pda4meAuthor Commented:
Perfect, thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.