I know this is duplicate question. But I have tried all the answers which I have found on the https://stackoverflow.com/ .
I think in my case I am inserting and updating data if same date match than record will update if not than it will insert.
Below is my file code:
<?php
if ( isset( $_POST['submit'] ) && $_POST['upload-csv'] == 'upload' ) {
$error = array();
$success = array();
$filename = $_FILES['file']['name'];
$filetype = wp_check_filetype( $filename );
if ( $filetype['ext'] == 'csv' && $filetype['type'] == 'text/csv' ) {
$handle = fopen( $_FILES['file']['tmp_name'], "r" );
$row = 0;
$skip_row_number = array("1");
while ( ($data = fgetcsv( $handle, 1000, "," )) !== FALSE ) {
$data = array_map("utf8_encode", $data);
if ($row > 0)
{
$table_name = $wpdb->prefix . 'prayer';
$ipquery = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `date` = '".$data[0]."'");
$query_res = $wpdb->num_rows;
// Check if same date data
if($query_res >=1){
$updateQuery = "UPDATE `$table_name` SET
`date` = '".$data[0]."',
`first_start` = '".$data[1]."',
`first_end` = '".$data[2]."',
`second_start` = '".$data[3]."',
`second_end` = '".$data[4]."',
`third_start` = '".$data[5]."',
`third_end` = '".$data[6]."',
`forth_start` = '".$data[7]."',
`forth_end` = '".$data[8]."',
`five_start` = '".$data[9]."',
`five_end` = '".$data[10]."',
`done` = '".$data[10]."'
WHERE `$table_name`.`date` = '".$data[0]."';";
$up_res = $wpdb->query($updateQuery);
}else{
$query = "INSERT INTO $table_name (date, first_start, first_end, second_start,
second_end, third_start, third_end, forth_start, forth_end, five_start, five_end, done)
VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."')";
$insert_res = $wpdb->query($query);
}
}
$row++;
}
fclose( $handle );
$success[] = 'Import done.';
} else {
$error[] = 'Please upload CSV file only';
}
}
?>
I have tried the below answer for skip the header:
Skip the first line of a CSV file
Import CSV, exclude first row
skip first line of fgetcsv method in php
Help me sort out this issue.
ParseCSV is latest and easy way to get data from CSV and you can get control of data from CSV easily.
in which you have to add library file as per proper path
e.g. require_once 'parsecsv.lib.php';
After then it return title and data seperately.
$filename = 'abc.csv'; // path of CSV file or after upload pass temp path of file
$csv = new parseCSV();
$csv->auto($filename);
foreach ($csv->titles as $value):
$getcsvtitle[] = // get header in variable
endforeach;
foreach ($csv->data as $key => $row):
//$getdataasperrow = // get data row wise.
endforeach;
ParseCSV return data in array format after just adding library, so you can easily separate header and other data, and compatible to new line and special character as well as i have been always using it as well.
Please refer below link for further detail as well.
ParseCSV GitHub
Related
Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.
Here i have a csv file which have contains numerous contacts rows, and these rows ae saved to my database table. Now i just want to inspect empty rows from uploaded csv by customer.
Here is an example csv with some empty rows
In this above csv, have 3rd and 6th rows are empty. so want to inspect these empty row number and discard csv with error.
Here is my csv code
$filename = $_FILES["csv_file"]["tmp_name"];
if ($_FILES["csv_file"]["size"] > 0) {
$file = fopen($filename, "r");
$importdata = fgetcsv($file, 10000, ",");
$counter = 1;
while (!feof($file)) {
if ($counter > 1) {
$alldata[] = fgetcsv($file);
}
$counter++;
}
fclose($file);
$csvfieldcounter = 1;
foreach ($alldata as $importdata) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
$status = 'Y';
if ($importdata[4] == 'Disable' || $importdata[4] == 'disable')
$status = 'N';
else if ($importdata[4] == 'Enable' || $importdata[4] == 'enable')
$status = 'Y';
$data = array(
'customer_name' => $importdata[0],
'customer_email' => $importdata[1],
'customer_mobile' => $importdata[2],
'birth_date' => $importdata[3],
'status' => $status,
'user_id' => $userId,
'cat_type' => $file_cat
);
if ($importdata[2]) {
$run = $this->db->insert('customer', $data);
$csvfieldcounter++;
$id = $this->db->insert_id();
}
}
$this->session->set_flashdata('csv_imported','Your CSV have been successfully imported.');
redirect('/customer', $csvfieldcounter);
}
I just want a little help for get that. your kind efforts would be appreciated Thanks :)
I suggest you to use below mentioned library. This will help you address above issue also it will decrease lines of code in your controller.
https://github.com/parsecsv/parsecsv-for-php
This will help you.
If you worried about how to use than check below mentioned code.
$this->load->library('Parsecsv');
$csv = new Parsecsv($file);
$users = $csv->data;
$noOfUsers = count($users);
foreach($users as $user):
if(!empty($user)):
// Write your code
endif;
endforeach;
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.
Im having a excel sheet with the format 10/12/2012.then i convert it into csv file i have a date as "41253",When i import that into my database it is storing as 0000-00-00. How to convert the date format while importing. or is there any other way?.
This is the code im using to import to database
if(isset($_POST['Submit']))
{
GLOBAL $HTTP_POST_FILES;
//$path= $HTTP_POST_FILES['ufile']['name'];
$path= $_FILES['ufile']['name'];
//
if(copy($_FILES['ufile']['tmp_name'], $path))
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="xyz"; // Database name
$tbl_name="productsegmentmaster"; // Table name
require_once '.\phpExcelReader\Excel\reader.php';
$excel = new Spreadsheet_Excel_Reader();
$excel->setOutputEncoding('CP1251');
$excel->read($path);
$x=2;
$sep = "*";
ob_start();
while($x<=$excel->sheets[0]['numRows']) {
$y=1;
$row="";
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
$row.=($row=="")?"".$cell."":"".$sep."".$cell."";
$y++;
}
echo $row."\n";
$x++;
}
//echo "Sheet count:$x";
$fp = fopen("data.csv",'w');
fwrite($fp,ob_get_contents());
fclose($fp);
//echo"----";
ob_end_clean();
//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("AmaraRaja",$connect); //select the table
//$file = $_FILES['data.csv']['tmp_name'];
$handle = fopen('data.csv',"r");
//loop through the csv file and insert into database
global $data;
do {
//echo "$data[0]";
//echo "$data[1]";
//echo "$data[2]";
//$post['ProductSegmentCode'] = $data[0];
// $post['ProductSegment'] = $data[1];
// $post['ProductGroup'] = $data[2];
$post['ProductCode'] = $data[0];
$post['WarrantyPeriod'] = $data[1];
$post['ProRataPeriod'] = $data[2];
$test = date("Y-m-d",strtotime($data[3]));
$post['ManufactureDate'] = $test;
$test1 = date("Y-m-d",strtotime($data[4]));
echo $data[4];
$post['ApplicableFormDate'] = $test1;
$tname = "productwarranty";
try
{
if($data[0]!="")
{
$news->addNews($post,$tname);
//mysql_query("INSERT INTO productsegmentmaster VALUES ( '$data[0]', '$data[1]','$data[2]')");
}
}
catch(Exception $e)
{
echo $e.getMessage();
}
} while ($data = fgetcsv($handle,1000,"*","'"));
echo"<script>alert('File $path Imported Successfully')</script>";
}
fclose($handle);
unlink('data.csv');
unlink($path);
}
?>
Sadly, I have the same exact problem! I tried the format way, didn't work!
I don't know if it's applicable to you, but a solution that I came with was put a apostrophe in front of it! ('YYYY/mm/dd). The Excel itself omit the apostrophe and only show data AS TEXT, not as a Excel timestamp. In that way you can explode the data by "/" and put it in the way you want.
BUT, if is impossible to you put a apostrophe in front in every one of them, you can verifiy if is a number and try to convert the excel timestamp to unix timestamp, assuming you server a *NIX like.
=)
I know it isn't the best solution, but so far is what I can get. Hope it helps you.
Try This
$date_format = floor($excelDateTime);
$time_format = $excelDateTime - $date_format;
$mysql_strdate = ($date_format > 0) ? ( $date_format - 25569 ) * 86400 + $time_format * 86400 : $time_format * 86400;
$mysql_date_format = date("Y-d-m", $mysql_strdate);
I'm trying to write and download CSV file using php. So every time file is created, file size is being attached in the last line. Like, if file size is 10kb, then the file result is
Viwed Date Product Name Viwed Item Username User Email
16-04-2012 i3 Primary Mathematics neha_new neha_new#mailinator.com
16-04-2012 i3 Primary III neha_new neha_new#mailinator.com
16-04-2012 i3 Primary i3 Primary neha_new neha_new#mailinator.com
Here is the code
if($_POST['report_format']=='csv') {
$csv_rows[] = array('Viewed Date','Product Name','Viewed Item','Username','User Email');
$da = db_query($sql);
while($data = db_fetch_object($da)) {
$partid = db_query("select name from term_data where tid=".$data->ptid);
$product_name = db_result($partid);
if($data->type=='term') {
$catid = db_query("select name from term_data where tid=".$data->tid);
$cat_name = db_result($catid);
} elseif($data->type=='node') {
$term_node = node_load($data->tid);
$cat_name = $term_node->title;
}
else {
$term_node = node_load($data->tid);
$cat_name = $term_node->field_read_image_field[0]['filename'];
}
$u = user_load($data->uid);
csv_rows[] = array(date('d-m-Y', $data->date), $product_name, $cat_name, $u->name, $u->mail);
}
foreach($csv_rows as $csvrow) {
$csvdata .= implode(',',$csvrow)."\n";
}
$file_path = $base_url."/sites/default/files/";
$fp = fopen("sites/default/files/user_csv/account_report.csv", "w") or exit("Unable to open file!");
fwrite($fp, $csvdata,strlen($csvdata)-1);
fclose($fp);
$url = $base_url.'/sites/default/files/user_csv/report_csv.php';
header("Location: ".$url);
}