1

I wonder if someone could actually show me a sample PHP code on how can i export around 50 tables in a MySQL database to a CSV file. My database name is "samples" and i have around 49 tables under this database. I want each tables (which has around 20,00 rows) under this database to be exported to a csv file.

Thank you and looking forward for any help. Sorry by the way, I'm very new in PHP.

1
  • do you use something like phpmyadmin or some other gui for database management? Commented Feb 27, 2014 at 15:38

4 Answers 4

2

If you have access to the MySQL server, you can use SELECT INTO OUTFILE to do most of this for you:

SELECT * FROM my_table
  INTO OUTFILE 'my_table.csv'
  FIELDS TERMINATED BY ','
  OPTIONALLY ENCLOSED BY '"'
  ESCAPED BY '\\'
  LINES TERMINATED BY '\n';

You may want to have a line delimiter of \r\n if you're using Windows.

If you don't specify a full path to the resulting CSV file it goes into the data directory of the MySQL server right beside the tables.

Sign up to request clarification or add additional context in comments.

Comments

0

Normally I would do this with something like MySQL Workbench or SQLYog. But if you need it in php there are some great tutorials on exporting from sql to php out there.

Something like this would work, but you would need to loop through the tables:

http://www.ineedtutorials.com/code/php/export-mysql-data-to-csv-php-tutorial

Comments

0

This is how to export 1 table directly from mysql terminal. I've just used the tmp directory as an example buy you can change the path to anything you like:

select * from product where condition1 order by condition2 desc INTO OUTFILE   '/tmp/myfile.csv' FIELDS    TERMINATED BY ',' ESCAPED BY '\\' OPTIONALLY ENCLOSED BY '"';

or with php and mysqli:

<?php
$con=mysqli_connect("example.com","uname","password","my_db");
 // Check connection
if (mysqli_connect_errno())
 {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 $result = mysqli_query($con,"  select * from product where condition1 order by condition2 desc INTO    OUTFILE   '/tmp/myfile.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';");

1 Comment

The double quote in your string isn't escaped is it?
0
Try...
Create csv file.
<?php 
mysql_connect('localhost', 'root', '');
mysql_select_db('mydb');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
  $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
$file = 'file.csv';
file_put_contents($file, $data);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.