2014-02-27 156 views
1

我不知道是否有人可以真正向我展示一個PHP代碼示例,我如何將大約50個表中的MySQL數據庫導出到CSV文件。我的數據庫名稱是「樣本」,我在這個數據庫下有大約49個表格。我希望這個數據庫下的每個表(有大約20,00行)被導出到一個csv文件。從mysql導出mysql列表到csv文件使用php

謝謝你,並期待着任何幫助。對不起,我很新的PHP。

+0

你使用的東西,像phpMyAdmin或者其他一些GUI來進行數據庫管理? –

回答

1

如果你有機會到MySQL服務器,你可以使用SELECT INTO OUTFILE做這個最適合你:

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

你可能想,如果你使用的是Windows擁有的\r\n一個行分隔符。

如果您沒有指定生成的CSV文件的完整路徑,它將進入MySQL服務器的數據目錄,就在表旁邊。

0

這是如何直接從mysql終端導出1個表。我剛剛使用的tmp目錄作爲一個例子給你買可以將路徑更改爲你喜歡的東西:

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

或PHP和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 '"';"); 
+0

你的字符串中的雙引號不會被轉義嗎? – tadman

+0

斑點tadman :) – Volterony

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); 
?>