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 ha
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.
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
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 '"';");
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);
?>