pda4me
asked on
MySQL SHOW COLUMNS but only those I select using PHP?
I am using the following code to generate a csv file and as you can see the SHOW COLUMNS MySQL query is used to generate the Column headings in the CSV. How do I get this query to display just the columns I have specified in the second query instead of all the table headings?
<?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.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT COLUMN1, COLUMN2, COLUMN3 FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$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;
?>
ASKER
when I do that it prints the column names where the data should be?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That is AWESOME! Thanks!
ASKER
AWESOME!!!
Try:
$csv_output = '';
$sql = mysql_query("SELECT column_1, column_3, column_3 FROM table") or die( 'Error' . mysql_error() );
$row = mysql_fetch_assoc($sql);
$i = 0;
while($row = mysql_fetch_assoc($sql))
{
if( $i == 0 )
{
foreach($row as $key=>$val)
{
$csv_output .= $key . ',';
}
$csv_output = rtrim($csv_output, ',') . "\r";
}
else
{
foreach($row as $key=>$val)
{
$csv_output .= $val . ',';
}
$csv_output = rtrim($csv_output, ',') . "\r";
}
$i++;
}
Open in new window