Esportare tabelle MySQL in CSV

Aprile 30, 2008

Eccovi una risorsa che può tornare utile nel caso si necessiti di esportare i dati contenuti nelle tabelle di database mysql in Comma Separated Value. L’ho ricavato modificando un vecchio tutorial trovato non so dove, l’ho testato personalmente su win e linux. pare che funzioni.

<?php
$host = ‘localhost’;
$user = ‘db_UserName’;
$pass = ‘db_UserPass’;
$db = ‘nome_database’;
$table = ‘nome_tabella’;
$file = ‘esporta’;

$link = mysql_connect($host, $user, $pass) or die(”Connessione Fallita.” . mysql_error());
mysql_select_db($db) or die(”Connessione Fallita.”);

$result = mysql_query(”SHOW COLUMNS FROM “.$table.”");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].”, “;
$i++;
}
}
$csv_output .= “\n”;

$values = mysql_query(”SELECT * FROM “.$table.”");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].”, “;
}
$csv_output .= “\n”;
}

$filename = $file.”_”.date(”Y-m-d_H-i”,time());
header(”Content-type: application/vnd.ms-excel”);
header(”Content-disposition: csv” . date(”Y-m-d”) . “.csv”);
header( “Content-disposition: filename=”.$filename.”.csv”);
print $csv_output;
exit;
?>

Entry Filed under: Scripts. Tag: , .

Leave a Comment

You must be logged in to post a comment.

Trackback this post  |  Subscribe to the comments via RSS Feed


Categorie

Articoli Recenti

Tag