PhpExcel inserts data more than once - insert

I have a PHP script that opens and reads an excel file and then inserts to a MySQL database The trouble I am experiencing for a while now is that although the var_dump of the insert to db query displays the correct amount of records (which will not be more that 60 records) when I view the database tables there are sometimes 154 records? I have searched and searched for a few days and am not able to rectify the problem.
Can anyone spot something in my code that could be causing this? I am a bit stumped as I say the var_dump of the insert query shows correct amount of records inserted...
<?PHP
include_once 'includes/functions/dbfunctions.php';
$link = dbConnect();
require_once "includes/Classes/PHPExcel.php";
$file= "flt_plan_input.xlsx";
$output = '';
$objPHPExcel = PHPExcel_IOFactory::load($file); // create object of PHPExcel library by using load() method and in load method define path of selected file
$output .= "<label class='text-success'>Data Inserted</label><br /><table width=\"100%\"class='table table-bordered' >";
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$highestRow = $worksheet->getHighestRow();
for($row=2; $row<=$highestRow; $row++){
$output .= "<tr>";
$year = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(0, $row)->getFormattedValue());
$schedule = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(1, $row)->getFormattedValue());
$sector = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(2, $row)->getFormattedValue());
$type = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(3, $row)->getFormattedValue());
$reg = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(4, $row)->getFormattedValue());
$civalue = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(5, $row)->getFormattedValue());
$fltnum = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(6, $row)->getFormattedValue());
$airline = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(7, $row)->getFormattedValue());
$orig = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(8, $row)->getFormattedValue());
$dest = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(9, $row)->getFormattedValue());
$pax = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(10, $row)->getFormattedValue());
$cargo = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(11, $row)->getFormattedValue());
$date = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(12, $row)->getFormattedValue());
$deph = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(13, $row)->getFormattedValue());
$depm = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(14, $row)->getFormattedValue());
$steh = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(15, $row)->getFormattedValue());
$stem = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(16, $row)->getFormattedValue());
$taxiout = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(17, $row)->getFormattedValue());
$taxiin = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(18, $row)->getFormattedValue());
$units = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(19, $row)->getFormattedValue());
$oew= mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(20, $row)->getFormattedValue());
$mzfw= mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(21, $row)->getFormattedValue());
$mtow= mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(22, $row)->getFormattedValue());
$mlw= mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(23, $row)->getFormattedValue());
$max_fuel_capacity = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(24, $row)->getFormattedValue());
$passenger_weight= mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(25, $row)->getFormattedValue());
$etops = mysqli_real_escape_string($link, $worksheet->getCellByColumnAndRow(26, $row)->getFormattedValue());
$query = "INSERT INTO flight_plan_fuel_input_data(year,schedule,sector,type,reg,civalue,fltnum,airline,orig,dest,pax,cargo,date,deph,depm,steh,stem,taxiout,taxiin,units,oew,mzfw,mtow,max_fuel_capacity,passenger_weight,etops,date_added)
VALUES('".$year."','".$schedule."','".$sector."','".$type."','".$reg."','".$civalue."','".$fltnum."','".$airline."','".$orig."','".$dest."','".$pax."','".$cargo."','".$date."','".$deph."','".$depm."','".$steh."','".$stem."','".$taxiout."','".$taxiin."','".$units."','".$oew."','".$mzfw."','".$mtow."','".$max_fuel_capacity."','".$passenger_weight."','".$etops."','".date("Y-m-d H:i:s")."')";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die( "Error: " . ((is_object($link)) ? mysqli_error($link) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) );
var_dump($query);
}
//$lastid = mysqli_insert_id($link);
//if($result){
//$sql = "DELETE FROM flight_plan_fuel_input_data where schedule = ''";
//$result = mysqli_query($GLOBALS["___mysqli_ston"], $sql) or die( "Error1: " . ((is_object($link)) ? mysqli_error($link) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) );
//}
$output .= '</tr>';
$output .= '</table>';
}
header("Location: view_loaded_flights.php");
?>

Related

Cannot set new image name in codeigniter

I'm uploading multiple image in codeigniter, But when i set new name using this code $_FILES['attachment']['name']= $filename;
I'm getting
The filetype you are attempting to upload is not allowed.
Please suggest solution to solve this issue.
public function do_upload()
{
if (($_SERVER['REQUEST_METHOD']) == "POST") {
$count = count($_FILES['attach_file']['name']);
$files = $_FILES;
for($i=0; $i<$count; $i++){
$filename = $_FILES['attach_file']['name'][$i];
$filename = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename = strstr($email, '#', true)."_".$filename;
$filename = strtolower($filename);
$_FILES['attachment']['name']= $filename;
$_FILES['attachment']['type']= $_FILES['attach_file']['type'][$i];
$_FILES['attachment']['tmp_name']= $_FILES['attach_file']['tmp_name'][$i];
$_FILES['attachment']['error']= $_FILES['attach_file']['error'][$i];
$_FILES['attachment']['size']= $_FILES['attach_file']['size'][$i];
$config['upload_path'] = FCPATH .'./assets/attachments/new/';
$config['allowed_types'] = 'pdf|doc|docx|bmp|gif|jpg|jpeg|jpe|png';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['encrypt_name'] = true;
$config['file_ext_tolower'] = true;
$config['overwrite'] = false;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('attachment')) {
$data['exception'] = $this->upload->display_errors();
$data['status'] = false;
echo json_encode($data);
} else {
$upload = $this->upload->data();
$data['message'] = 'upload_successfully';
$data['filepath'] = './assets/attachments/'.$upload['file_name'];
$data['status'] = true;
echo json_encode($data);
}
}
}
}
Note:- You are assign same variable name again & again $filename
Please Change this:-
$filename = $_FILES['attach_file']['name'][$i];
$filename = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename = strstr($email, '#', true)."_".$filename;
$filename = strtolower($filename);
$_FILES['attachment']['name']= $filename;
to :-
$filename = $_FILES['attach_file']['name'][$i];
$filename1 = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename2 = strstr($email, '#', true)."_".$filename1;
$filename3 = strtolower($filename2);

Laravel - "Unable to write in the "/var/www/html/laraapp/public/storage/documents/appraisal_goal" directory"

I deployed my Laravel-5.8 application on Digital Ocean which uses Ubuntu-18. When I wanted to save image into my Laravel App on Digital Ocean:
public function create()
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$employees = DB::table('hr_employees')->select('id')->where('id', $userEmployee)->first();
// dd($employees);
$goaltypes = AppraisalGoalType::where('company_id', $userCompany)->get();
$categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('appraisal.appraisal_goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities)
->with('employees', $employees)
;
}
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$employees = DB::table('hr_employees')->select('id')->where('id', $employeeId)->first();
DB::beginTransaction();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $request->employee_id; //$employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
foreach ( $request->activity as $key => $activity){
$startDate = Carbon::parse($request->start_date[$key]);
$endDate = Carbon::parse($request->end_date[$key]);
$goaldetail = new AppraisalGoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->appraisal_doc = $request->application_doc[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->start_date = $startDate ->toDateTimeString();
$goaldetail->end_date = $endDate->toDateTimeString();
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->appraisal_identity_id = $goal->appraisal_identity_id;
$goaldetail->employee_id = $goal->employee_id;
$goaldetail->company_id = Auth::user()->company_id;
$goaldetail->created_by = Auth::user()->id;
$goaldetail->created_at = date("Y-m-d H:i:s");
$goaldetail->is_active = 1;
$goaldetail->save();
}
$min_date = AppraisalGoalDetail::select('start_date')->where('appraisal_goal_id', $goal->id)->min('start_date');
$max_date = AppraisalGoalDetail::select('end_date')->where('appraisal_goal_id', $goal->id)->max('end_date');
$parentid = AppraisalGoalType::select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$goal->update([
'appraisal_start_date' => $min_date,
'appraisal_end_date' => $max_date,
'parent_id' => $parentid->parent_id
]);
DB::commit();
Session::flash('success', 'Appraisal Goal is created successfully');
return redirect()->route('appraisal.appraisal_goals.index');
} catch (Exception $exception) {
dd($exception->getMessage());
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return redirect()->route('appraisal.appraisal_goals.index');
}
}
Everything works perfectly on the local server. But when I deployed it online to Digital Ocean. Then, when I click on submit, I got this error:
"Unable to write in the "/var/www/html/laraapp/public/storage/documents/appraisal_goal" directory"
How do I resolve it?
Thank you
You do not have necessary permission to write in storage folder.
Execute below command to provide necessary permission to write in storage folder
chmod 755 -R /var/www/html/laraapp/public/storage
chown www-data:www-data /var/www/html/laraapp/public/storage

function str_slug is deprecated and not working, what should i do?

I was trying to use Str_slug but it is not working in laravel 5.8.
I am using PhpStorm latest version.
$product->slug = Str_slug('$request->title');
Check the image for more
public function ProductStore(StoreValidation $request){
$product = new product();
$product->category_id = 1;
$product->brand_id = 1;
$product->title = $request->title;
$product->desc = $request->desc;
$product->slug = Str_slug('$request->title');
$product->quantity = $request->quantity;
$product->price = $request->price;
$product->offer_price = $request->offer;
$product->status = 1;
$product->admin_id = 1;
// Saving Product information into product table
$product->save();
if ($request->hasFile('uploadFile')){
$image = $request->file('uploadFile');
$img = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('image/product/' .$img);
$img_ins = Image::make($image)->resize(220,294);
$img_ins->save($location);
$product_img = new product_image();
$product_img->product_id = $product->id;
$product_img->image_name = $img;
$product_img->save();
}
return redirect()->route('admin_panel.pages.admin-addProduct');
}
You should use Str::slug() (Illuminate\Support\Str) instead of deprecated str_slug().
https://laravel.com/docs/5.8/helpers#method-str-slug

In controller its saving the image and how can i resize it to 150,150

its working but how to resize image in it
public function store(Request $request)
{
$input = $request->all();
$image = Input::file('image');
if (isset($image)) {
$directory = public_path() . '/uploads/programs';
$medium_size = public_path() . '/uploads/programs/100X100/';
$thumb_nails = public_path() . '/uploads/programs/100X100/';
if (!file_exists($directory)) File::makeDirectory($directory, 0777, true, true);
$filename = sha1(time() . time()) . ".png";
$filename = $image->getClientOriginalName();
$filename = str_random(40) . "$filename";
$upload_success = $image->move($directory, $filename);
$input['image'] = $filename;
}
product::create($input);
return redirect('home');
}

Resize Gif without losing animation using the library image_lib, Codeigniter

I Want how to resize a Gif without losing the animation using Codeigniter with the image_lib It's possible?
there my function
public function crop($width, $height, $xaxis, $yaxis, $img)
{
$img = is_file(_UPLOADS_DIR_ . $img) ? $img : 'placeholder.jpg';
$ext = substr($img, strrpos($img, '.') + 1);
$img_name = str_replace('.' . $ext, '', $img);
$file_name = $img_name . '-' . $width . '-' . $height . '-' . $xaxis . '-' . $yaxis . '.' . $ext;
if (!is_file(_THUMBS_DIR_ . $file_name)) {
log_message('info', 'Create thumb: '.$file_name);
$config = array();
$config['source_image'] = _UPLOADS_DIR_ . $img;
$config['new_image'] = _THUMBS_DIR_ . $file_name;
list($w, $h) = getimagesize($config['source_image']);
$canvas_ratio = $width / $height;
$img_ratio = $w / $h;
$config['width'] = round(($canvas_ratio > $img_ratio) ? $width : $height / $h * $w);
$config['height'] = round(($canvas_ratio < $img_ratio) ? $height : $width / $w * $h);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$config = array();
$config['source_image'] = _THUMBS_DIR_ . $file_name;
$config['maintain_ratio'] = false;
$config['width'] = $width;
$config['height'] = $height;
list($w, $h) = getimagesize($config['source_image']);
$config['x_axis'] = ($xaxis > 0) ? ($width - $w) * ($xaxis / -100) : 0;
$config['y_axis'] = ($yaxis > 0) ? ($height - $h) * ($yaxis / -100) : 0;
$this->image_lib->initialize($config);
$this->image_lib->crop();
chmod(_THUMBS_DIR_ . $file_name, 777);
}
switch ($ext) {
case 'jpg':
case 'jpeg':
header('Content-Type: image/jpg');
break;
case 'png':
header('Content-Type: image/png');
break;
case 'gif':
header('Content-Type: image/gif');
break;
}
readfile(_THUMBS_DIR_ . $file_name);
}

Resources