Cant upload .csv file into db using php? - php

Here is the code, which is written for uploading .csv file using php. but I get an error as
Warning:
fopen(excel/) [function.fopen]:
failed to open stream: No such file or directory
in C:\xampp\htdocs\interfaceasia\dealer_portal\upload\index.php on line 49
which is the line
if(($handle = fopen("excel/".$fileName , "r")) !== FALSE)
Can someone help on what has gone wrong here.
if($_FILES['csvFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file");
$row=0;
if(($handle = fopen("excel/".$fileName , "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
print_r($data);
$query="INSERT INTO dealer_tbl(title,firstname,lastname,email,phone)VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')";
mysql_query($query);
}
fclose($handle);
}
}

you need a folder called
C:\xampp\htdocs\interfaceasia\dealer_portal\upload\excel
and of course you need a file in there
and whats also important, in your line....
if(($handle = fopen("excel/".$fileName , "r")) !== FALSE)
$filename seems to be empty at all
because error says something like this
fopen(excel/)
there are some more errors
if($_FILES['csvFile']['name']!="")
{ //___^^^^^^^^____here you have csvFile
$fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file");
//____________________________^^^^^^^^^^____here you have excelFile
you really should take care the upload befor trying to enhance your script :)
if($_FILES['csvFile']['tmp_name']!="")
move_uploaded_file($_FILES['csvFile']['tmp_name'], "excel/myFile.csv");

Related

Read CVS file and ouput the CSV file to .txt file

Hi here I am reading a CSV file and I am trying to write the CSV file data into a .txt file.
$row = 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
$myfile = fopen("newfile.txt", "w") or die ("unable to open file");
fwrite($myfile, $data[$c]);
}
}
fclose($handle);
}
The newfile.txt are being created and only the last record in the CSV file are showing in the newfile.txt. Can anyone tell me why everything in the CSV are not showing in my newfile.txt(only the last record are displaying). Thank You
You only need to open the new file once.
$row = 1;
if (($handle = fopen("data.csv", "r")) && $myfile = fopen("newfile.txt", "w")) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
fputcsv($myfile, $data);
}
fclose($handle);
fclose($myfile);
}
Open your file with a+ parameter instead of w for fopen.
From the doc, the mode 'w' opens for writing only, while the mode 'a+' opens for reading and writing and place the file pointer at the end of the file. If the file does not exist, it attempts to create it.
$row = 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
$myfile = fopen("newfile.txt", "a+") or die ("unable to open file");
fwrite($myfile, $data[$c]);
}
}
fclose($handle);
}
You are opening the file on every loop iteration which not a good idea try putting it above the loop
Use a+ mode instead of w in the fopen reference
this is probably because you reopen your textfile everytime you write a record and overwrite its content. Either open the file in append mode (can't tell you how, I am not a php programmer) or open your textfile only once and write several times in one session.
Edit: You should use 'a' or 'a+' instead of 'w' as parameter for fopen as explained here: http://php.net/manual/en/function.fopen.php

Skip first line of fgetcsv method

I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which'll contain any header. I am using this code.
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
// Code to insert into database
}
When I insert data into th database then header should not to be saved into the database.
Before beginning the while loop, just get the first line and do nothing with it. This way the logic to test if it's the first line is not needed.
fgetcsv($file, 10000, ",");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
//....
}
try:
$flag = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
// rest of your code
}
A bit late, but here is another way to do so (without having to count all the lines): with fgets
$file = fopen($filename, 'r'); // create handler
fgets($file); // read one line for nothing (skip header)
while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
// do your thing
}
One might consider this to be more elegant
You can add a simple check and skip the query if the check fails:
$firstline = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
if (!$firstline) {
// Code to insert into database
}
$firstline = false;
}
Try this simple code.
$file = fopen('example.csv', 'r'); // Here example is a CSV name
$row = 1;
while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
// $line is an array of the csv elements
if($row == 1){ $row++; continue; } // continue is used for skip row 1
// print_r($line);
// rest of your code
}
You should use the fseek() method in order to get the desired line, regardless the current pointer position.
At this example, get the first line after the loop:
$file = fopen($path, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
// ...
}
fseek($file, 1, SEEK_CUR);
You can use the third parameter to position the pointer in the file, as is:
SEEK_SET – It moves file pointer position to the beginning of the file.
SEEK_CUR – It moves file pointer position to given location.
SEEK_END – It moves file pointer position to the end of file.

merger the csv data with php?

There are many CSV file like the following:a.csv, b.csv, aab.csv etc.
They hold the same column and header. Now I want to put all the csv data into whole.csv. With only one header. How can I do it?
a.csv data:
header1 title post.....
test who posand
b.csv data:
header1 title post.....
head she pnow
etc .....
The whole.csv will contain all the csv data.
eg:
header1 title post.....
head she pnow
test who posand
I tried the following code.but not get I want to:
$csvs = glob("*.csv");
foreach($csvs as $csv) {
$row = 1;
if (($handle = fopen($csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$fp = fopen("whole.csv", 'w');
fputcsv($fp, $data);
$row++;
}
fclose($handle);
}
}
I have put all CSV files in the same directory.
For every input csv file you are opening the resultant csv file in write mode:
$fp = fopen("whole.csv", 'w');
which wipes the content of the whole.csv!!
You need to open the whole.csv file just once outside the loop and keep writing into it.
$csvs = glob("*.csv");
$fp = fopen("whole.csv", 'w');
foreach($csvs as $csv) {
$row = 1;
if (($handle = fopen($csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
fputcsv($fp, $data);
$row++;
}
fclose($handle);
}
}
Have a look at file_put_contents.
You would open each CSV file, then use file_put_contents passing whole.csv as the $filename parameter, the file handle as the $data parameter and use the FILE_APPEND flag to tell it to append the contents instead of overwriting.

update one column record in a csv with php

there are two columns in my csv file,eg:
image gallery
/1.jpg /a.jpg;/b.jpg
..... .....
now i want to update the gallery content to /1.jpg;/a.jpg;/b.jpg. namely,add the content of image collumn and ; to the gallery content.
the following is my code.when i run it. it can't update the content of the csv.i am get stucked.
$dir = getcwd();
$files = scandir($dir);
foreach ($files as $file) {
$parts = pathinfo($file);
if ($parts['extension']!="csv") {
continue;
}
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
$data[1]=$data[0].";".$data[1];
fputcsv($file, $data);
}
fclose($handle);
}
open file in write or append mode and
fputcsv expects first parameter to be resource and you have given file path
which is causing problem
change it
fputcsv($handle, $data);
Please check the file permission first and after that you have to change the handle to both read and write and also please check whether the data[1] is having the values.
Because in Your code the the data[0] only will fetch the lines as a string which is separated with ";" so you have to explode it and after that do the operations.

CSV import via PHP

I'm importing a .CSV into an application with the following:
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
It sort of works but it's far from perfect. I wanted to first get out the row heads and put them into an array and then loop round each row to get the data sets in.
It seems to be having delimitting problems as the first row (heads) are also including a few parts of the second row.
I exported the .csv file straight from Excel. Wonder if there are encoding tricks etc I might be missing.
It sounds like your 1000 limit is not long enough; you should set it to a high enough value for that file ... or set to 0 for unlimited (not recommended, because it tends to be slower).
Set it to 4096 or 8192 first and see how it goes.
// use 8kB buffer for reading comma delimited line
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
Update
Okay, on second thought, perhaps you should inspect the file and confirm a few things:
Are the delimiters really a comma? (I guess you've already established this)
Are the string enclosures always double quotes?
Are strings escaped with a backslash (default) or another double quote?
fgetcsv doesnt always properly detect line endings.
Try using before the fgetcsv call:
ini_set('auto_detect_line_endings', true);
I changed to 8192 and got same results
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
...
}
and then did this one and got same results
$handle = fopen($_FILES['filename']['tmp_name'], "r");
ini_set('auto_detect_line_endings', true);
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
$data = array_map('mysql_real_escape_string', $data);
Why are you not using file()?
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Categories