I want to import CSV file data to MySQL.
This is the code:
if (is_uploaded_file($_FILES['excelfile']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['excelfile']['name'] ." Upload Done!" . "</h1>";
echo "<h2>File Upload:</h2>";
readfile($_FILES['excelfile']['tmp_name']);
}
$handle = fopen($_FILES['excelfile']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into city(city_name,days) values('$data[0]','$data[1]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
echo "<br><strong>Import Done.</strong><br>
The result just inserts into one column:
The fields in your CSV file are separated by semicolon, but you're using comma in your call to fgetcsv(). Try
while ($data = fgetcsv($handle, 1000, ";")) {
You can get the data on CSV file following code.
if ($_FILES['excelfile']['size'] > 0) {
$mimes = array('application/vnd.ms-excel', 'text/plain', 'text/csv', 'text/tsv');
//get the csv file
$file = $_FILES['excelfile']['tmp_name'];
$handle = fopen($file, "r");
$data = array();
while (!feof($handle)) {
$data[] = fgetcsv($handle);
}
}
Now you have data of CSV on $data array.So using foreach and then you can insert data into database.
Related
I have a csv file like this:
I would like to concatenate the values of the style_color columns in this csv file. To have for example SCJEG4_1014.
I wrote a script, it creates this last column with the header 'Pictures Names' but in each cell I just have "_".
How can I solve my problem?
<?php
//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);
// Excel in CSV
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load($xlsx);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$nomcsv = "C:/wamp64/www/Extract_pictures_Excel/csv/".date('Ymd_His').".csv";
$writer->save($nomcsv);
$delimiter = ";";
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$names_pictures = $data[7].'_'.$data[4];
$csv_data[] = $data;
$row++;
}
fclose($handle);
}
$extra_columns = array('Pictures Names' => $names_pictures);
foreach ($csv_data as $i => $data) {
if ($i == 0) {
$csv_data[$i] = array_merge($data, array_keys($extra_columns));
} else {
$csv_data[$i] = $data = array_merge($data, $extra_columns);
}
}
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
?>
It looks like you only add in the details from the last row ( as you only use the value of $names_pictures once). It would be better (IMHO) to add this value into the data at the point at which you generate the $csv_data array...
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$data['Pictures Names'] = $data[7] . '_' . $data[4];
$csv_data[] = $data;
$row++;
}
You could then remove the foreach ($csv_data as $i => $data) { loop
If you had a different file for the output you could open the output file before the above loop and write the data directly to the output file rather than using $csv_data...
if (($handle = fopen($nomcsv, 'r')) !== FALSE
&& ($ohandle = fopen($nomcsvOutput, 'w')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$data['Pictures Names'] = $data[7] . '_' . $data[4];
fputcsv($ohandle, $data, $delimiter);
}
fclose($handle);
fclose($ohandle);
}
I have a code where a csv file is uploaded ,the data is extracted from it and uploaded to database.Everything works fine,but how can i skip the empty rows and continue reading the rows with data in it.
This is the code where i extract data from csv file
if (($source = fopen( $csv_file, "r")) !== FALSE)
{
//read data from excel
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
$question=$data[0];
$point=$data[1];
$header=$data[2];
$footer=$data[3];
$type_value=$data[4];
$group_name=$data[5];
echo $question;
}// while end
}
If you use PHP's SplFileObject instead of the basic fgetcsv() function, it has built-in options to skip empty lines:
$file = new SplFileObject($csv_file);
$file->setFlags(SplFileObject::READ_CSV SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
foreach ($file as $data) {
...
}
if ($data[0] == NULL)
continue;
This is because fgetcsv returns a non-empty array with a null element inside.
Try it with
if ($data === null) continue;
I didn't test it, but I sthink it should work.
Try this
if (($source = fopen( $csv_file, "r")) !== FALSE)
{
// read data from excel
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
if ((string) $data[0] != '0' and empty($data[0]))
{
continue;
}
$question = $data[0];
$point = $data[1];
$header = $data[2];
$footer = $data[3];
$type_value = $data[4];
$group_name = $data[5];
echo $question;
}
}
I'm trying to recieve data from a .csv. Here the code I have so far:
if(($handle = fopen("test.csv", "r")) !== FALSE){
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
}
}
But this puts all the data I need in the first entry in the $data array. What I need to do is $data[1] and then get all the values from the second column. I've done it before but I can't it to work this time. How do I do it?
EDIT
Here is my .csv file structure
| ID | Name |
|------|----------|etc
| 1 |Product 1 |
Here's a screenshot of the file http://imgur.com/BlaCvjo
And with echo $data[1] it should return 'Product 1'
Please be specific to your question. Anyway, these codes will help you to your question.
<?php
$csv = array();
// check there are no errors
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$col_count = count($data);
// get the values from the csv
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[2];
// inc the row
$row++;
}
fclose($handle);
}
}
}
?>
getHistory downloads a CSV file from Yahoo finance API, i am trying to get the CSV file, and insert the symbol infront of each of the entries in the file. After that is done i want to write the CSV file back to $symbol.csv. My data is the way i want it, i just cant seem to write it to a CSV file. What am i doing wrong? Or is there a better way to go about this?
$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if($row = 1){array_unshift($data,"Symbol"); }
else { array_unshift($data, "T"); }
$fp = fopen('t.csv', 'w');
fputcsv($fp, $data);
fclose($fp);
$row++;
}
}
fclose($handle);
In your loop, you are opening and closing the file on each iteration. You should open the csv file before the loop, add to it, then close it when the loop is done.
Also, you should use === or == for comparisons.
$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
// This truncates the file to zero length
// so, we only need to do this once, before the loop
$fp = fopen('t.csv', 'w');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if($row === 1){array_unshift($data,"Symbol"); }
else { array_unshift($data, "T"); }
fputcsv($fp, $data);
$row++;
}
// Close it once we're all done
fclose($fp);
}
fclose($handle);
I have a table name tblstuden. It contains ids studentname, rollnumberm and classname. I want to download this data in CSV format. How is it possible?
I can upload the data into the table by CSV file. To upload the code is below. It's working for me. But now I want to download the data in CSV format.
<?php
if(isset($_POST['submit']))
{
$row = 1;
$file1 = $_FILES['file']['tmp_name'];
$file = fopen($file1, "r");
while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$data[$c];}
echo $data[0];
$name = $data[0];
}
fclose($file);
?>
You can download a csv file using this code.
$getRecord = mysql_query("SELECT id, studentname, rollnumber, classname FROM tblstuden");
while ($row = mysql_fetch_array($getRecord )) {
$csvFile .= $row['id'].",". $row['studentname'].",". $row['rollnumber'].",".$row['classname']."\r\n";
}
header("Content-type: application/octet-stream");
header("Content-disposition:attachment; filename="."testCSV.csv");
echo $csvFile;