SQL result into CSV

I have the results of a SELECT statement being written into an html table. What would be the simplest way to get these results exported into a CSV?

The code Im using to get the initial result is :

$sql="SELECT * FROM gbu0_prod" ;
			$result =mysql_query($sql);
			while ($data=mysql_fetch_assoc($result)){
			?>
				<tr>
					<td><?php echo $data['id']; ?></td>	
					<td><?php echo $data['name']; ?></td>	
					<td><?php echo $data['descshort']; ?></td>	
					<td>http://www.websiteurl/media/gbu0/prodsm/<?php echo $data['imgsm']; ?></td>	
					<td>http://www.websiteurl/gbu0-prodshow/<?php echo $data['id']; ?>.html</td>	
					<td><?php echo $data['regprice']; ?></td>	
					<td><?php echo $data['brand']; ?></td>	
					<td>new</td>	

				</tr>
			<?	
			}
                       ?>

I know there are a few similar threads on the forum which I have looked at but I was unable to get any of them to work out.

I am unsure about how you want it to be output. Generally something like the below should do.

$csv = '';
$f = 1;

while ($entry = fetch_assoc) {
	
	if ($f) {

		$csv .= "id = $entry['id']. name = entry['name'] etc";
		$f = 0;

	} else {

		$csv .= ", id = $entry['id']. name = $entry['name'] etc";

	}

}

If you are outputting to a file you might want to use fputcsv.

yeah, Im looking to output to a file which I can then open in excel.

Do I need to loop around each line I normally display? ie

$csv .= "id = $entry['id']. name = entry['name'], "name = $entry['name']. name = entry['name'],"descshort = $entry['descshort']. name = entry['name'],ect ";

thanks.

Hi, sorry for the delay. I have never done what you are describing, importing csv files to excel tables, before. So I went ahead and tried it out. May be good to know about. Also my connection was very unresponsive for some reason and I restarted the wlan card.

It is necessary I think that you need to loop through each row of the result. Whether you call fputcsv in each iteration or write with standard file handling functions ought to make no difference.

You can also concatenate it to a variable and write the variable to a file. Just make sure to output it in the intended format.

P.S. Note that you need braces when you want to parse array elements within a double quoted string. For example; “id = {$entry['id]}”.