Jump to content

MySQL to CSV export


_spaz

Recommended Posts

Is it possible to export SQL results from multiple tables to CSV format?  I have a query that joins multiple tables in a database and I would like it to export that data to CSV, here's my SQL query:

 

SELECT MediaFile.id, MediaFile.filename, MediaFile.createtime, JobMediaFile.starttime, JobMediaFile.endtime, JobMediaFile.progress, Job.name, SummaryAlert.title, FileStatus.status

FROM MediaFile

LEFT JOIN JobMediaFile ON JobMediaFile.mediafile_id = MediaFile.id

LEFT JOIN Job ON JobMediaFile.job_id = Job.id

LEFT JOIN SummaryAlert ON JobMediaFile.id = SummaryAlert.jobmediafile_id

LEFT JOIN FileStatus ON FileStatus.Mediafile_id = MediaFile.id

GROUP BY MediaFile.id

Link to comment
https://forums.phpfreaks.com/topic/175815-mysql-to-csv-export/
Share on other sites

fputcsv($resource, $fields), handles this beautifully!

 

Great thanks, this is the code that I'm currently using and it works great.  Is there a way to display the Field names for each column?

 

<?php

 

 

 

mysql_connect("192.168.0.184","root","vtec19");

 

// Select the database

$db_select=mysql_select_db("CerifyDB");

 

define('CSV_SEPERATOR',';');

define('CSV_PATH','\\');

define('CSV_FILENAME','data.csv');

 

 

$_POST[keyword] = Canwest;

 

$result = mysql_query("SELECT MediaFile.id, MediaFile.filename, MediaFile.createtime, JobMediaFile.starttime,    JobMediaFile.endtime, JobMediaFile.progress, Job.name, SummaryAlert.title, FileStatus.status

          FROM MediaFile

LEFT JOIN JobMediaFile ON JobMediaFile.mediafile_id = MediaFile.id

      LEFT JOIN Job ON JobMediaFile.job_id = Job.id

      LEFT JOIN SummaryAlert ON JobMediaFile.id = SummaryAlert.jobmediafile_id

      LEFT JOIN FileStatus ON FileStatus.Mediafile_id = MediaFile.id

  WHERE MediaFile.filename LIKE '%$_POST[keyword]%' GROUP BY MediaFile.id");

 

$fp = fopen(CSV_FILENAME, 'w');

if ($fp == false) {

  die("Could not open data.csv for writing");

 

 

}

 

 

while ($record = mysql_fetch_row($result)) {

  fputcsv($fp, $record);

 

}

 

echo '<a href="' . CSV_PATH . CSV_FILENAME . '" target="_blanc">CSV File</a>';

fclose($fp);

?>

Link to comment
https://forums.phpfreaks.com/topic/175815-mysql-to-csv-export/#findComment-926795
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.