/var/log/step2k

July 10, 2006

Upload Csv Insert To MySql

Filed under: Project, MySQL, PHP - Salman Teguh @ 2:46 am

from : http://howto.indika.net.id/wikka.php?wakka=UploadCsvInsertToMySql
< ?php
//First we need to define our user pass and database name
$tbl = “yourtablename”;
$host=”yourdatabasehost”;
$user=”youruser”;
$pass=”yourpass”;
$database=”yourdatabase”;

//we need function to get the csv
function getcsv($filename, $delim =”,”){

$row = 0;
$dump = array(); //create new array for hold the data csv

$f = fopen ($filename,”r”);
$size = filesize($filename)+1;
while ($data = fgetcsv($f, $size, $delim)) {
$dump[$row] = $data; //put the data to array
//echo $data[1].”
“;
$row++;
}
fclose ($f);

return $dump;
}

//this function for insert data to csv
function makeINSERTS($text, $table){
global $linkdata; //make global database connection
$insert = array(); //make array for hold data insert
$i = 0;

while (list($key, $val) = @each($text)){
//insert the data
$insert[$i] = “INSERT into “.$table.” VALUES('’,'”;
$insert[$i] .= implode(”‘,’”, $val);
$insert[$i] .= “‘)\n”;
$result = mysql_query($insert[$i], $linkdata) or die(’Query failed: ‘ . mysql_error());
$i++;
}

return $insert;

}

//this verify is the file csv upload
if ($_POST[”submit”]==”submit”) {
if (is_uploaded_file($_FILES[’userfile’][’tmp_name’])) {

$file=$_FILES[’userfile’][’tmp_name’];
$linkdata = mysql_connect($host, $user, $pass)
or die(’Could not connect: ‘ . mysql_error());

mysql_select_db($database) or die(’Could not select database’);

$CSVarray = getcsv($file);
$CSVarray = makeINSERTS($CSVarray, “$tbl”);

} else {
echo “error upload file”;
exit;
}

} else {
//form upload
echo “

Upload this file:

“;
}
?>

Comments »

The URI to TrackBack this entry is: http://step2k.blogsome.com/2006/07/10/upload-csv-insert-to-mysql/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


Get free blog up and running in minutes with Blogsome
Theme designed by Alex King