Hello all.
Here I have a script that will take my uploaded CSV and break it down into an html table for me to display, and then insert each row one by one into the database.
<edit>
Not sure how, but I fixed the looping problem. Now it wont insert into the DB. It doesnt give errors at all either. It just skips over the while statment at the end for the inserts.
</edit>
Can some please help me fix this!
Also, if you can suggest a better or quicker method to read from a csv insert the info into a DB and how to read a TAB DELIMITED file, please share!
Thanks!
<?php
if($stop_exe == FALSE){
$path = $site_dir."/wm/";
$show_upload = "Y";
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$start_1 = microtime_float();
if(is_uploaded_file($file_name)){
$file_tmp_name = $file_name;
$file_name = $_FILES['file']['name'];
$move_csv = move_uploaded_file($file_tmp_name, $path.$file_name);
if($move_csv){
chmod($path.$file_name, 0644);
} else {
$msg = "Could not upload ".$file_name." to ".$core_dir."wm";
}
} else {
$msg = $file_name." was not uploaded to be moved.";
}
$end_1 = microtime_float();
echo "Uploaded ".filesize($path.$file_name)." byte file in ".($end_1 - $start_1)." seconds.";
//start tricky stuff
$start_2 = microtime_float();
$csv_read = fopen($path.$file_name, "r");
while(($data = fgetcsv($csv_read, filesize($path.$file_name)+1, ",")) !== FALSE){
$data = str_replace('"', '', $data);
$csv[] = $data;
}
if($show_upload == "Y"){
//show me whatcha got!
echo "<table>";
foreach($csv as $row){
echo "<tr>";
foreach($row as $col){
echo "<td>".$col."</td>";
}
echo "</tr>";
}
echo "</table>";
//hide yo stuff!
}
$row_num = 1;
while(list($key, $val) = each($csv)){
if($row_num != 1){
$sql = mysql_query("INSERT INTO ".$prefix."store_wholesale VALUES ('".implode("','", $val)."')") or die(mysql_error());
}
$row_num++;
}
$end_2 = microtime_float();
echo "Read and inserted ".$row_num." rows in ".($end_2 - $start_2)." seconds.";
$msg = $file_name." imported.";
//end tricky stuff
}
?>