PHP Update MySQL from CSV Skip Row on Error - php

So basically, I have a CSV file that will be uploaded but not stored on the server and PHP will pull data from it and update a database accordingly.
My Issue is that I am trying to skip the row in the CSV if there is already an entry found in the database but it stops on the first error and does not skip.
Line 62, I added a comment which is where I am trying to get this accomplished.
the ELSE statement after the if (($update == 1) && ($update2 == 1)) has a continue in it, meaning if update and update2 do not == 1 then skip, or so I would have thought but it just stops after the first duplicate serial number is found.
Any help is GREATLY appreciated
public function upload() {
$this->data['token'] = $this->session->data['token'];
$connect = mysqli_connect("localhost", "username", "password", "database");
$this->load->model('setting/mail');
if (isset($_POST["upload"])) {
if ($_FILES['update_cases']['name']) {
$filename = explode(".", $_FILES['update_cases']['name']);
if (end($filename) == "csv") {
$handle = fopen($_FILES['update_cases']['tmp_name'], "r");
fgetcsv($handle);
$this->load->model('sale/order');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
print "row start<br>";
$order_id = mysqli_real_escape_string($connect, $data[0]);
$product_sn = mysqli_real_escape_string($connect, $data[1]);
$customer_email = mysqli_real_escape_string($connect, $data[2]);
$status = mysqli_real_escape_string($connect, $data[13]);
$rma_number = mysqli_real_escape_string($connect, $data[17]);
$rma_type = mysqli_real_escape_string($connect, $data[18]);
$planned_product = mysqli_real_escape_string($connect, $data[19]);
$tur = mysqli_real_escape_string($connect, $data[20]);
$pi = mysqli_real_escape_string($connect, $data[21]);
$cir = mysqli_real_escape_string($connect, $data[22]);
$cmr = mysqli_real_escape_string($connect, $data[23]);
$waive_return = mysqli_real_escape_string($connect, $data[24]);
$replacement_tracking = mysqli_real_escape_string($connect, $data[26]);
$inventory = mysqli_real_escape_string($connect, $data[27]);
$replacement_sn = mysqli_real_escape_string($connect, $data[28]);
$replacement_sn2 = mysqli_real_escape_string($connect, $data[29]);
$qty_shipped = mysqli_real_escape_string($connect, $data[33]);
$date_shipped = mysqli_real_escape_string($connect, $data[35]);
$result1 = $this->model_sale_order->getOrderById($order_id);
$current_status = $result1['order_status'];
$rma_num = $result1['order_rma'];
$customer_id = $result1['cus_id'];
$regpro_id = $result1['regpro_id'];
$update = 0;
$update2 = 0;
$batch_data = array(
"order_id" => $order_id,
"rpl_tracking" => $replacement_tracking,
"qty_shipped" => $qty_shipped,
"replacement_sn" => $replacement_sn,
"replacement_sn2" => $replacement_sn2,
"inventory" => $inventory,
"rma_type" => $rma_type,
"pi_num" => $pi,
"tur_num" => $tur,
"cir_num" => $cir,
"cmr_num" => $cmr,
"waive_return" => $waive_return,
"update_status" => $status,
"date_shipped" => $date_shipped,
"pre_status" => $current_status,
"comment" => $planned_product,
"planned_product" => $planned_product
);
if ($qty_shipped !== 0) {
$this->load->model('catalog/product');
$this->load->model('catalog/regproduct');
// If Two replacement products
if ($qty_shipped == 2) {
//Check if Serial Number Already Exists (If exists, I want the script to skip this row and move onto the next row in the excel sheet)
$check_sn = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn);
$check_sn2 = $this->model_catalog_regproduct->checkSNBelong2($replacement_sn2);
if ($check_sn) {
$update = 0;
$this->error['error_replacement_sn'] = "SN " . $replacement_sn . " in use!";
} else {
$update = 1;
}
if ($check_sn2) {
$update2 = 0;
$this->error['error_replacement_sn2'] = "SN " . $replacement_sn2 . " in use!";
} else {
$update2 = 1;
}
if (($update == 1) && ($update2 == 1)) {
$replacement_product = $this->model_catalog_product->getProductBySN($replacement_sn);
$replacement_product2 = $this->model_catalog_product->getProductBySN($replacement_sn2);
$defective_product_warranty = $this->model_catalog_regproduct->getRegproductById($customer_id, $regpro_id);
$warr_date = $defective_product_warranty['regpro_warr_date'];
$replacement_model = $replacement_product['m_type'];
$replacement_model2 = $replacement_product2['m_type'];
$replacement_family = $replacement_product['f_type'];
$replacement_family2 = $replacement_product2['f_type'];
$this->model_catalog_regproduct->addRegproductReplacement2($customer_id, $replacement_sn2, $replacement_family2, $replacement_model2, $warr_date);
$this->model_catalog_regproduct->addRegproductReplacement($customer_id, $replacement_sn, $replacement_family, $replacement_model, $warr_date);
$this->model_sale_order->confirmOrder3($this->user->getId(), $batch_data);
if (((int)$current_status) !== ((int)$status)) {
if ((int)$status == 210) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_PRODUCT_RECEIVED_STANDARD');
}
} elseif ((int)$status == 230) {
if ($rma_type != "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_ADVANCED');
} elseif ($rma_type == "Standard") {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_REPLACEMENT_PRODUCT_SHIPPED_STANDARD');
}
} elseif ((int)$status == 500) {
$template = $this->model_setting_mail->getTemplateByLabel('RMA_CLOSED');
}
if ((int)$template['email_status'] == 1) {
$subject = $template['email_subject'];
$message = $template['email_content'];
// Get Customer Email
$this->load->model('sale/customer');
$order_info = $this->model_sale_customer->getCustomerByEmail($customer_email);
$customer_info = $this->model_sale_customer->getCustomer($order_info['cus_id']);
$email = $customer_info['cus_username'];
$this->load->model('sale/order');
$result_tracking = $this->model_sale_order->getOrderById($order_id);
$replacement_tracking = $result_tracking['order_return_tracking_num'];
$message = str_replace('%FIRSTNAME%', $customer_info['cus_firstname'], $message);
$message = str_replace('%LASTNAME%', $customer_info['cus_lastname'], $message);
$message = str_replace('%RMA%', $rma_num, $message);
$message = str_replace('%TRACKING%', $replacement_tracking, $message);
$mail = new Mail();
$mail->protocol = $this->config->get('mail_protocol');
$mail->hostname = $this->config->get('smtp_host');
$mail->username = $this->config->get('smtp_username');
$mail->password = $this->config->get('smtp_password');
$mail->port = $this->config->get('smtp_port');
$mail->timeout = $this->config->get('smtp_timeout');
$mail->setTo($email);
$mail->setFrom($this->config->get('sender_email'));
$mail->setSender($this->config->get('sender_name'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
try {
$mail->send();
}
catch(Exception $e) {
$this->error['warning'] = $e->getMessage();
}
}
}
$this->session->data['success'] = $this->language->get('text_success');
//$this->redirect($this->url->link('report/sale_return', 'token=' . $this->data['token'], 'SSL'));
} else {
print $update."<br>";
print $update2."<br>";
print "Errors<br>";
continue;
}
//row start
//0
//0
//Errors
//row start
//0
//0
//Errors
//row start
//row end
//row start
//row end
//row start
//row end
} else if ($qty_shipped == 1) {
// will do something else
} else if ($qty_shipped == 0) {
// will also do something else
}
} else if (!isset($qty_shipped)) {
// will also do something else
}
print "row end<br>";
}
}
}
}
}

If you want to show all errors, you should use an array, and append the error text to that array. Then use foreach loop on client part to display all errors.
If you use a single variable it will always be what you set it to most recently. For multiple data, you should use an array, or append to string like this: $string .= "appended string"; but for this case I recommend using arrays.

Related

unable to insert multiple array data from dynamic generated field?

I am unable to enter multiple data, it enter only single data. I have tried using for loop and then entering data, using 3 user and 2 task, there is an error previously offset.
public function add($postData)
{
// dd($postData);
$c = count($postData['user_name']);
$t = count($postData['task_name']);
for ($i = 0; $i < $c; $i++) {
$user_name = $postData['user_name'][$i];
$user_email = $postData['user_email'][$i];
$data['insert']['user_name'] = $user_name;
$data['insert']['user_email'] = $user_email;
}
for ($j = 0; $j < $t; $j++) {
$task_name = $postData['task_name'][$j];
$data['insert']['task_name'] = $task_name;
}
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
if ($result == true) {
$response['status'] = 'success';
$response['message'] = 'Project created';
} else {
$response['status'] = 'danger';
$response['message'] = DEFAULT_MESSAGE;
}
return $response;
}
As Per lack of question details attached, I am supposing that you want to insert multiple task entry with project name, description etc.
Here is updated code:
<?php
// dd($postData);
$username = $postData['username'];
$user_email = $postData['user_email'];
$task_name = $postData['task_name'];
foreach ($username as $key => $value) {
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['username'] = $value;
$data['insert']['user_email'] = $user_email[$key];
$data['insert']['task_name'] = $task_name[$key];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
}

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

Laravel - Import excel keep looping

Dears,
i have an excel file with 5K rows and i'm importing it to my table in the DB successfully.
But the error, when the system finish all the rows, it keeps looping and the page doesn't stop running and not redirecting to my view.
My controller:
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->select('id')->get()->toArray();
if(empty($res)) {
$polic = new policies();
$polic->cust_id = $row['custno'];
$polic->policy = '';
$polic->bord_date = $borddate;
$polic->client_id = $row['clientid'];
$polic->client_no = $row['clientno'];
$polic->client_name = $row['clientname'];
$polic->draft_no = $row['draftno'];
if ($row['status'] == '') {
$polic->status = '';
} else {
$polic->status = $row['status'];
}
$polic->due_date = $duedate;
if ($row['curno'] == 'USD') {
$polic->currency = 1;
} else {
$polic->currency = 0;
}
$polic->amount = $row['amnt'];
$polic->zone = $row['zone'];
$polic->broker_id = $row['brokercode'];
$polic->broker_name = $row['brokername'];
$polic->remarks = $row['remarks'];
$polic->phone = $row['phone'];
$polic->insured_name = $row['insname'];
// $polic->cust_id = $row['valuedate'];
$polic->address = ''; //address
if (trim($row['status']) == 'P') {
$polic->paid_at = date('Y-m-d');
}
$polic->new = 1; //address
$polic->save();
}
else {
//am updating the imported date in the DB
}
what is very strange that in my localhost is working fine, but in digitaloceans cloud, keep looping without redirecting.
Thanks for your help.
I can be because you have 5000 rows to insert and 5000 insert operation consumes lots of memory. What you can try is batch insert operation.
In your policies.php make all fields fillable
protected $fillable=['cust_id ','policy','bord_date','client_id','client_no','client_name ','draft_no','bord_date','status','due_date','currency','amount','zone','broker_id','broker_name','remarks','phone','insured_name','address','paid_at','new'];
And on your excel file import use exists rather than getting collections.
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
$data=[];
$i=0;
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->exists();
if(!$res) {
$i++;
$data[$i]['cust_id ']=$row['custno'];
$data['policy'] = '';
$data['bord_date'] = $borddate;
$data[$i]['client_id'] = $row['clientid'];
$data[$i]['client_no'] = $row['clientno'];
$data[$i]['client_name'] = $row['clientname'];
$data[$i]['draft_no'] = $row['draftno'];
if ($row['status'] == '') {
$data[$i]['status'] = '';
} else {
$data[$i]['status'] = $row['status'];
}
$data[$i]['due_date'] = $duedate;
if ($row['curno'] == 'USD') {
$data[$i]['currency'] = 1;
} else {
$data[$i]['currency'] = 0;
}
$data[$i]['amount'] = $row['amnt'];
$data[$i]['zone'] = $row['zone'];
$data[$i]['broker_id'] = $row['brokercode'];
$data[$i]['broker_name'] = $row['brokername'];
$data[$i]['remarks'] = $row['remarks'];
$data[$i]['phone'] = $row['phone'];
$data[$i]['insured_name'] = $row['insname'];
// $data[$i]['cust_id'] = $row['valuedate'];
$data[$i]['address'] = ''; //address
if (trim($row['status']) == 'P') {
$data[$i]['paid_at'] = date('Y-m-d');
}
$data[$i]['new'] = 1; //address
}
else {
//am updating the imported date in the DB
}
}
policies::insert($data);

Unable to maintain Session in Laravel

I'm using Laravel 5.3 and facing problems regarding the session which is not being preserved when I hit the URL with query string(UTM Querystring). It works fine without querystring and maintains the session.
mywebsite.com/booking (Works fine)
mywebsite.com/booking?utm_source=affiliate&utm_medium=mailer&utm_campaign=Ad2click (Destroys session as well cookies)
Wondering, what could be the reason?
public function bookProduct(Request $request){
$zone = $request->zone;
$records = Zone::where('zone_name',$zone)->get();
foreach($records as $record){
$zone_id = $record->id;
}
if ( Session::get('LAST_ACTIVITY') && (time() - Session::get('LAST_ACTIVITY') > 1200 )){
echo 'expired';
}
else{
$CheckOTP = Session::get('otp');
/* Check if User Entered OTP Matches System Generated OTP */
if ( $CheckOTP == $request->get_otp ) {
/* Create new Customer */
$recordCount = Customer::where('email', $request->customer_email)->orWhere('contact_number',$request->customer_contact_no)->count();
if( $recordCount > 0 ){
Customer::where('contact_number', $request->customer_contact_no)->update(['door_number' => $request->customer_pickup_door_no, 'building_name' => $request->customer_pickup_building_name, 'street_name' => $request->customer_pickup_street_name, 'area' => $request->customer_pickup_area, 'landmark' => $request->customer_pickup_landmark, 'pincode' => $request->customer_pickup_pincode, 'city'=>$request->customer_city]);
}
if($recordCount == 0 || $recordCount == ""){
$customer = new Customer;
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$randomPass = implode($pass);
$password = Hash::make('a');
$customer->customer_name = $request->customer_name;
$customer->email = $request->customer_email;
$customer->contact_number = $request->customer_contact_no;
$customer->password = $password;
$customer->door_number = $request->customer_pickup_door_no;
//$customer->street_name = $request->customer_pickup_street_name;
//$customer->building_name = $request->customer_pickup_building_name;
$customer->area = $request->customer_pickup_area;
$customer->landmark = $request->customer_pickup_landmark;
$customer->pincode = $request->customer_pickup_pincode;
$customer->city = $request->customer_city;
$customer->save();
$id = $customer->id;
$measurement = new Measurement;
$measurement->customer_id = $id;
$address = $request->customer_pickup_door_no .",".$request->customer_pickup_area .",".$request->customer_pickup_landmark .",". $request->customer_city.",". $request->customer_pickup_pincode;
$measurement->save();
$datas = $this->create_customer($request->customer_contact_no,$request->customer_name, $request->customer_email,$address,$request->customer_pickup_pincode);
$this->save_customers($request->customer_contact_no);
}
else{
$address = $request->customer_pickup_door_no .",".$request->customer_pickup_area .",".$request->customer_pickup_landmark .",". $request->customer_city.",". $request->customer_pickup_pincode;
$datas = $this->create_customer($request->customer_contact_no,$request->customer_name, $request->customer_email,$address,$request->customer_pickup_pincode);
$this->save_customers($request->customer_contact_no);
$fetchCustomer = Customer::where('email', $request->customer_email)->orWhere('contact_number',$request->customer_contact_no)->get();
foreach( $fetchCustomer as $customerId ){
$id = $customerId->id;
}
}
/* Store New Booking */
/* Pickup address same as shipping address*/
if( $request->duplicate_address == 'on'){
$request->customer_shipping_door_no = $request->customer_pickup_door_no;
//$request->customer_shipping_street_name = $request->customer_pickup_street_name;
//$request->customer_shipping_building_name = $request->customer_pickup_building_name;
$request->customer_shipping_area = $request->customer_pickup_area;
$request->customer_shipping_landmark = $request->customer_pickup_landmark;
$request->customer_shipping_pincode = $request->customer_pickup_pincode;
}
$booking = new Booking;
$booking->customer_id = $id;
$booking->look_id = Session::get("lookIds");
$booking->time_slot_id = $request->slot;
$booking->booking_date = strtr($request->booking_date, '/', '-');
$booking->booking_date = date('Y-m-d', strtotime($booking->booking_date));
$booking->door_number = $request->customer_shipping_door_no;
//$booking->street_name = $request->customer_shipping_street_name;
//$booking->building_name = $request->customer_shipping_building_name;
$booking->landmark = $request->customer_shipping_landmark;
$booking->pincode = $request->customer_shipping_pincode;
$booking->city = $request->customer_city;
$booking->area = $request->customer_shipping_area;
$booking->fabric_availability = $request->fabric_material;
$booking->otp = $CheckOTP;
$booking->http_user_agent = $_SERVER['HTTP_USER_AGENT'];
$zones = Zone::where('zone_name',$request->zone)->get();
foreach( $zones as $zone){
$booking->zone_id = $zone->id;
}
/* Fetch Latitude & Longitude from address */
//$address = $request->customer_pickup_door_no.' ,'.$request->customer_pickup_street_name.' ,'.$request->customer_pickup_building_name.' ,'.$request->customer_pickup_landmark;
$address = $request->customer_pickup_door_no.' ,'.$request->customer_pickup_landmark.' ,'.$request->customer_shipping_area;
$prepAddr = str_replace(' ','+',$address);
$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
if( $output->status != "ZERO_RESULTS" ){
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
}
else{
$booking->latitude = "";
$booking->longitude = "";
}
$lastId = Booking::max('id');
$lastId = $lastId+1;
$booking->booking_id = 'BK'.date("ymd").str_pad($lastId, 4, '0', STR_PAD_LEFT);
$checkCouponApply = $request->check_coupon_apply;
if($checkCouponApply == '1'){
$couponCode = $request->discount_coupon;
$booking->coupon_code = $request->discount_coupon;
$getDiscountPercentage = Discount::where('coupon_code',$couponCode)->pluck('coupon_percentage');
$getDiscountPercentage = $getDiscountPercentage[0];
Discount::where('coupon_code',$booking->coupon_code)->decrement('remaining_user_count');
}
$booking->save();
Session::set('bookingId', $booking->id);
if($request->trouser > 0 && $request->shirt > 0){
Session::set('productBought', 'Shirt & Trouser');
}
else if($request->trouser>0){
Session::set('productBought', 'Trouser');
}
else if($request->shirt>0){
Session::set('productBought', 'Shirt');
}
/* Store products data for Booking */
$trouserRecord = Categories::where('category_name','Trouser')->pluck('id');
$shirtRecord = Categories::where('category_name','Shirt')->pluck('id');
$trouserPrice = ProductPrice::where('zone_id',$zone_id)
->where('category_id',$trouserRecord[0])
->pluck('price');
$shirtPrice = ProductPrice::where('zone_id',$zone_id)
->where('category_id',$shirtRecord[0])
->pluck('price');
$shirtUnitPrice = $shirtPrice[0];
$trouserUnitPrice = $trouserPrice[0];
$products = array('trouser' => array('count' => $request->trouser, 'category' => $trouserRecord[0], 'price'=>$trouserPrice[0], 'unit_price'=>$trouserUnitPrice), 'shirt' => array('count' => $request->shirt, 'category' => $shirtRecord[0], 'price'=>$shirtPrice[0], 'unit_price'=>$shirtUnitPrice));
foreach($products as $product){
for($i=0;$i<$product['count'];$i++){
$subBooking = new SubBooking;
//Calculate tax tmount for each lined up product and save relavant data
$subBooking->booking_id = $booking->id;
if($product['category'] == '3'){
$subBooking->category_name = 'Shirt';
}
else if($product['category'] == '4'){
$subBooking->category_name = 'Trouser';
}
$setTaxes = Tax::all();
foreach($setTaxes as $taxes){
$tax[$taxes->tax_type] = $product['unit_price']*($taxes->percentage/100);
$tax[$taxes->tax_type.'Percentage'] = $taxes->percentage;
}
$subBooking->service_tax = $tax['Service Tax'];
$subBooking->service_tax_percentage = $tax['Service TaxPercentage'];
$subBooking->swachh_bharat = $tax['Swachh Bharat'];
$subBooking->swachh_bharat_percentage = $tax['Swachh BharatPercentage'];
$subBooking->krishi_kalyan = $tax['Krishi Kalyan'];
$subBooking->krishi_kalyan_percentage = $tax['Krishi KalyanPercentage'];
$subBooking->category_id = $product['category'];
$subBooking->unit_price = $product['unit_price'];
$subBooking->unit_price = $product['unit_price'];
$subBooking->quantity = 1;
$subBooking->save();
}
}
if($subBooking){
$this->storeReportingData('new');
}
$email = $request->customer_email;
$booking_date_new = date("d M Y", strtotime($booking->booking_date));
$time_slot_data = TimeSlot::where('id',$booking->time_slot_id)->first();
$start = date("g:i a", strtotime($time_slot_data['start']));
$end = date("g:i a", strtotime($time_slot_data['end']));
$msg = "Thank you for booking with us. Your booking ref number is: $booking->booking_id and our appointment with you is on $booking_date_new ($start - $end).";
$action = 'New Booking';
$description = "Booking has been created";
$this->saveLog($booking->id, $action, $description);
Session::forget('lookIds');
$contact_no = $request->customer_contact_no;;
$urlapi = "https://api-in.bsmart.in/api/v3/sendsms/plain?";
$user = "USER";
$password = "SECRET";
$senderid = "SENDER_ID";
$pin = mt_rand(1000, 9999);
$msg_order_confirmation = urlencode("$msg");
$msg2 = "Dear Customer, Please spare 45 minutes of your valuable time with our stylists for a perfect styling experience.";
$sms_url = $urlapi."User=".$user."&Password=".$password."&Sender=".$senderid."&GSM=91".$contact_no."&SMSText=".$msg_order_confirmation;
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sms_url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
$email_message = $msg." ".$msg2;
//$this->sendEmail($email,$email_message);
$this->sendSMS($contact_no,$msg2);
$sub_bookings = SubBooking::where('booking_id',$booking->id)->where('quantity','<>', 0)->get();
$data = array();
foreach($sub_bookings as $sub_booking){
$quantity = $sub_booking->quantity;
$category_data = Categories::where('id',$sub_booking->category_id)->first();
$category_name = $category_data['category_name'];
$data[] = array('quantity'=>$quantity,'category_name'=>$category_name);
}
$appointment_date = date("d M Y", strtotime($booking->booking_date));
$time_slot_data = TimeSlot::where('id',$booking->time_slot_id)->first();
$start = date("g:i a", strtotime($time_slot_data['start']));
$end = date("g:i a", strtotime($time_slot_data['end']));
$customer_data = Customer::where('id',$booking->customer_id)->first();
$customer_name = $customer_data['customer_name'];
$email_data = array('email'=>$email,'customer_name'=>$customer_name,'from'=>'notifications-noreply#raymondcustomtailoring.com','from_name'=>'Raymond','appointment_date'=>$appointment_date,'appointment_id'=>$booking->booking_id,'customer_name'=>$customer_name,'address'=>$address,'pincode'=>$request->customer_shipping_pincode,'data'=>$data,'start'=>$start,'end'=>$end);
/*Mail::send(['html'=>'confirm'],$email_data, function( $message ) use ($email_data)
{
$message->to( $email_data['email'] )->from($email_data['from'],$email_data['from_name'] )->subject($email_data['appointment_id'].' Appointment Confirmed');
});*/
//return $booking->id;
}
else{
echo 'mismatched';
}
}
}

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (Drupal + PHPexcel)

<?php
function import_sales_request(){
$hostname = '****';
$username = '****';
$password = '*****';
global $base_url;
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'UNSEEN', SE_UID);
$emailDates = array();
if ($emails) {
//$count = 1;
rsort($emails);
foreach ($emails as $email_number) {
$overview = imap_fetch_overview($inbox, $email_number, FT_UID);
$message = imap_fetchbody($inbox, $email_number, 2, FT_UID);
$structure = imap_fetchstructure($inbox, $email_number, FT_UID);
$emailDates[$email_number] = $overview[0]->date;
$message_header = imap_fetchheader($inbox, $email_number, 1);
$message_body = imap_fetchbody($inbox, $email_number, "1.1", FT_UID);
//file_put_contents(drupal_get_path('module', 'pricecal') . "/mail/" . $email_number . ".htm", nl2br($message_header) . $message_body);
$attachments = array();
if (isset($structure->parts) && count($structure->parts)) {
for ($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');
if ($structure->parts[$i]->ifdparameters) {
foreach ($structure->parts[$i]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if ($structure->parts[$i]->ifparameters) {
foreach ($structure->parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if ($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1, FT_UID);
if ($structure->parts[$i]->encoding == 3) {
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
} elseif ($structure->parts[$i]->encoding == 4) {
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
foreach ($attachments as $attachment) {
if ($attachment['is_attachment'] == 1) {
$filename = $attachment['name'];
$fileinfo = pathinfo($filename);
if (in_array($fileinfo['extension'], array('csv', 'xls', 'xlsx'))) {
if (empty($filename))
$filename = $attachment['filename'];
if (empty($filename))
$filename = time() . ".dat";
$fp = fopen(drupal_get_path('module', 'pricecal') . "/mail/".$email_number."-".clean($overview[0]->from). "-" . clean($filename), "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
}
//if($count++ >= $max_emails) break;
imap_setflag_full($inbox, $email_number, "\\Seen \\Flagged", ST_UID);
}
}
imap_close($inbox);
import_sales_request_into_database($emailDates);
return true;
}
/*
* Insert new and revised request into database
*/
function import_sales_request_into_database($emailDates = '', $flag = false) {
global $user;
global $base_url;
include_once(drupal_get_path('module', 'pricecal') . '/excel/Classes/PHPExcel/IOFactory.php');
$filelist = file_scan_directory(drupal_get_path('module', 'pricecal') . '/mail', '/^.*\.(csv|CSV|xls|XLS|xlsx|XLSX)$/');
if (!empty($filelist)) {
foreach ($filelist as $list) {
$objPHPExcel = PHPExcel_IOFactory::load($list->uri);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$resultArray = array();
$part_no = array();
$start_part_no = 0;
$temp = 0;
$ctoarray = array();
$transaction = db_transaction(); //start database transaction
try {
/*
* Prepare array structure to insert as a new or revised request
* $flag = true - it is not importing, it is from home page browse button
*/
$resultArray['requester_name'] = empty($sheetData[1]['B']) ? '' : $sheetData[1]['B'];
$resultArray['requester_email'] = empty($sheetData[2]['B']) ? '' : $sheetData[2]['B'];
$resultArray['request_number'] = empty($sheetData[3]['B']) ? '' : $sheetData[3]['B'];
$resultArray['customer_name'] = empty($sheetData[4]['B']) ? '' : $sheetData[4]['B'];
$resultArray['segment'] = empty($sheetData[5]['B']) ? '' : $sheetData[5]['B'];
$resultArray['dmu_cmr'] = empty($sheetData[6]['B']) ? '' : $sheetData[6]['B'];
$resultArray['cyborg_no'] = empty($sheetData[7]['B']) ? '' : $sheetData[7]['B'];
$resultArray['duty_type'] = empty($sheetData[8]['B']) ? '' : $sheetData[8]['B'];
$resultArray['country_code'] = empty($sheetData[9]['B']) ? '' : $sheetData[9]['B'];
$resultArray['billing_type'] = empty($sheetData[10]['B']) ? '' : $sheetData[10]['B'];
$resultArray['tier_1_partner'] = empty($sheetData[11]['B']) ? '' : $sheetData[11]['B'];
$resultArray['tier_2_partner'] = empty($sheetData[12]['B']) ? '' : $sheetData[12]['B'];
$resultArray['requested_tp'] = empty($sheetData[13]['B']) ? '' : (float)str_replace(',', '', $sheetData[13]['B']);
$resultArray['deal_justification'] = empty($sheetData[14]['B']) ? '' : $sheetData[14]['B'];
$cto_counter = 0 ;
$ctocounterarray = array();
if (!empty($sheetData)) {
foreach ($sheetData as $key => $value) {
if (!empty($resultArray)) {
if ($value['B'] == 'Part Number*') {
$start_part_no = $key;
}
if ($start_part_no != 0 && $key > $start_part_no && $value['B'] != '') {
if (($value['A'] == 'CTO' || $value['A'] == 'Regular') && $temp == 0) {
if($value['A'] == 'CTO'){
$part_no[] = array($value['B'] => array($value['C'], 'primary-cto'));
$cto_counter++;
$ctocounterarray[] = $value['B'];
}else{
$part_no[] = array($value['B'] => array($value['C'], 'primary'));
}
}
if ($value['A'] == 'Bundle-Base' && trim($value['B']) != "" && !empty($value['B'])) {
$temp = 1;
$new_part_number = $value['B'];
}
if ($temp) {
if($value['A'] == "Bundle-Remove"){
$value['C'] = -1 * abs($value['C']);
}
$part_no[] = array($value['B'] => array($value['C'], $value['A']));
$ctoarray[$new_part_number][] = array($value['B'] => array($value['C'], $value['A']));
}
if ($value['A'] == 'CTO' && $temp == 1 && in_array($value['B'], $ctocounterarray)) {
$temp = 0;
$cto_counter--;
}
}
$resultArray['part_no'] = $part_no;
}
}
}
$continue_flag = true;
if($cto_counter !== 0){
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
}
$newRequest = '';
$quotationSummary = '';
$quotationLineItems = array();
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
$date = date("Y-m-d H:i:s"); //insert current date time in database
$email_date = (isset($emailDates) && isset($emailDates[$mail_id]) && array_key_exists($mail_id, $emailDates)) ? date("Y-m-d H:i:s", strtotime($emailDates[$mail_id])) : $date;
if (!$flag) {
$result = db_select('quotation_request', 'qr')->fields('qr', array('email_number'))->condition('email_number', $mail_id, '=')->execute()->fetchAssoc();
if (!empty($result)) {
drupal_set_message(t($list->filename . ' already imported.' . PHP_EOL), 'warning');
//import_sales_request_logfile($list->filename, 2);
$continue_flag = false;
}
}
$request_type = 'new';
if ($continue_flag && !empty($resultArray)) {
$request_number = '';
if (empty($resultArray['request_number'])) {
$request_number = import_sales_request_number(); //if the request is new
} else {
$revision = '';
$revise_request_number = array(trim($resultArray['request_number']),trim($resultArray['request_number']).'_R1',trim($resultArray['request_number']).'_R2',trim($resultArray['request_number']).'_R3',trim($resultArray['request_number']).'_R4',trim($resultArray['request_number']).'_R5',trim($resultArray['request_number']).'_R6',trim($resultArray['request_number']).'_R7',trim($resultArray['request_number']).'_R8',trim($resultArray['request_number']).'_R19',trim($resultArray['request_number']).'_R10',trim($resultArray['request_number']).'_R11',trim($resultArray['request_number']).'_R12',trim($resultArray['request_number']).'_R13',trim($resultArray['request_number']).'_R14',trim($resultArray['request_number']).'_R15',trim($resultArray['request_number']).'_R16',trim($resultArray['request_number']).'_R17');
$result = db_select('quotation_request', 'qr')->fields('qr', array('request_number'))->condition('request_number',$revise_request_number , 'IN')->execute();
$revision = $result->rowCount();
if (!empty($revision) && $revision > 0) {
$request_number = $resultArray['request_number'] . '_R' . $revision;
$request_type = 'revise';
} else {
drupal_set_message(t($list->filename . ' has invalid request number.' . PHP_EOL), 'warning');
import_sales_request_logfile($list->filename, 3,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
}
}
/*
* If all OK then it will create a new or revised request in database
*/
if ($continue_flag) {
/*
* $newRequest - will have inserted request number
*/
try {
$newRequest = db_insert('quotation_request')->fields(array('email_number' => $mail_id, 'request_number' => $request_number,'request_type'=>$request_type, 'requester_name' => $resultArray['requester_name'], 'requester_email' => $resultArray['requester_email'], 'customer_name' => $resultArray['customer_name'], 'duty_type' => $resultArray['duty_type'], 'billing_type' => $resultArray['billing_type'], 'segment' => $resultArray['segment'],'request_file' => $list->filename, 'request_date_time' => $email_date, 'dmu_cmr' => $resultArray['dmu_cmr'], 'cyborg_no' => $resultArray['cyborg_no'], 'country_code' => $resultArray['country_code'], 'tier_1_partner' => $resultArray['tier_1_partner'], 'tier_2_partner' => $resultArray['tier_2_partner'], 'requested_tp' => $resultArray['requested_tp'], 'deal_justification' => $resultArray['deal_justification'], 'status' => 'generate quotation', 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($newRequest)) {
try {
$quotationSummary = db_insert('quotation_summary')->fields(array('quotation_request_id' => $newRequest, 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($quotationSummary) && !empty($resultArray['part_no'])) {
$base_part_no_id = 0;
foreach ($resultArray['part_no'] as $key => $value) {
$part_no = key($value);
$quantity = (isset($value[$part_no][0])) ? $value[$part_no][0] : 0;
$part_no_behaviour = (isset($value[$part_no][1])) ? $value[$part_no][1] : 'primary';
$query = db_select('cost_tape', 'ct')->fields('ct', array('cost_tape_id'))->fields('ctp', array('bmc_price'))->condition('ct.part_number', $part_no);
$query->leftJoin('cost_tape_price', 'ctp', 'ct.cost_tape_id=ctp.cost_tape_id');
$query->orderBy('ctp.created', 'DESC')->range(0, 1);
$resultArrayAssoc = $query->execute()->fetchAll();
if (count($resultArrayAssoc) > 0) {
foreach ($resultArrayAssoc as $node) {
$cost_tape_id = $node->cost_tape_id;
$bmc_price = $node->bmc_price;
$not_found_part_number = "";
}
} else {
$not_found_part_number = $part_no;
$cost_tape_id = null;
$bmc_price = 0.0;
}
if($part_no_behaviour == 'CTO' || $part_no_behaviour == 'primary-cto'){
$not_found_part_number = $part_no;
$not_found_part_desc = "Server";
$cost_tape_id = null;
}else{
$not_found_part_desc = "";
}
try {
$quotationLineItem = db_insert('quotation_lineitems')->fields(array('quotation_request_id' => $newRequest, 'quotation_summary_id' => $quotationSummary, 'cost_tape_id' => $cost_tape_id, 'not_found_part_no' => $not_found_part_number, 'not_found_desc' => $not_found_part_desc, 'part_behavior' => $part_no_behaviour, 'ref_id' => $base_part_no_id, 'bmc_price' => $bmc_price, 'qty' => $quantity, 'created' => $date, 'uid' => $user->uid))->execute();
$quotationLineItems[] = $quotationLineItem;
if ($part_no_behaviour == 'Bundle-Base' && isset($quotationLineItem)) {
$base_part_no_id = $quotationLineItem;
// $quotationLineItems[] = $quotationLineItem;
$num_updated = db_update('quotation_lineitems') // Table name no longer needs {}
->fields(array('ref_id' => $base_part_no_id))
->condition('quotation_lineitems_id', $base_part_no_id, '=')
->execute();
}
if ($part_no_behaviour == 'CTO' && $base_part_no_id != 0) {
$base_part_no_id = 0;
}
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
}
}
}
}
}
if ($continue_flag && $newRequest && $quotationSummary && !empty($quotationLineItems)) {
drupal_set_message(t($list->filename . ' imported successfully' . PHP_EOL));
import_sales_request_logfile($list->filename, 1);
$requester_name = $resultArray['requester_name'];
$requester_email_id = $resultArray['requester_email'];
$params = array(
'subject' => "Price quote request has been received successfully. Customer Name :- ".$resultArray['customer_name']. " Request No :- ".$request_number,
'body' => "<p>Hi ".$requester_name.",<br/></p>
<p>Thanks for your email. DCG Pricing team will work on your price quote request and will shortly share the quotation with you.</p>
<p>Your request number is ".$request_number.".</p>
<p>Customer Name : ".$resultArray['customer_name'].".</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>The dcgpricing#lenovo.com mailbox is dedicated to handle only price quote requests. For any other queries, please reach out to respective pricers.</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
drupal_mail('pricecal', 'success_sales_request', $resultArray['requester_email'], language_default(), $params);
$customer_name = $resultArray['customer_name'];
$params = array(
'subject' => "New price quote request received",
'body' => "<p>Hi Team,<br/></p>
<p>The DCG pricing tool has successfully uploaded a price quote input request and is now available for your working.</p>
<ul>
<li>Request Number : ".$request_number."</li>
<li>Customer name : ".$customer_name."</li>
<li>Requestor name : ".$requester_name."</li>
<li>Requestor email id : ".$requester_email_id."</li>
<li>Deal justification : ".$resultArray['deal_justification']."</li>
</ul>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
} else if ($continue_flag) {
$transaction->rollback();
//drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
} catch (Exception $e) {
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
rename($list->uri, drupal_get_path('module', 'pricecal') . '/tmp/' . $list->filename);
}
} else {
drupal_set_message(t('No email founds.' . PHP_EOL), 'warning'); //if no email found with unread status
}
return true;
}
/*
* Create new request number and check weather request number already exists
*/
function import_sales_request_number($length = 6) {
$selectPartId = db_query("select count(request_number) as request_number from quotation_request")->fetchAssoc();
if(empty($selectPartId['request_number'])){
$token = 101;
}else{
$token = $selectPartId['request_number'] + 101;
}
return $token;
}
function import_sales_request_logfile($filename = '', $update = 0,$requester_emailId = '',$requesterName = '') {
global $base_url;
$log_file_path = drupal_get_path('module', 'pricecal') . '/logs/' . date('Y-M-d') . '.dat';
$msg = ($update) ? $filename . ' imported success' . PHP_EOL : $filename . ' import failed' . PHP_EOL;
if ($update == 0) {
$msg = $filename . ' import failed' . PHP_EOL;
} else if ($update == 1) {
$msg = $filename . ' imported success' . PHP_EOL;
} else if ($update == 2) {
$msg = $filename . ' already imported' . PHP_EOL;
} else if ($update == 3) {
$msg = $filename . ' invalid request number' . PHP_EOL;
}
file_put_contents($log_file_path, date('h:i:sa ') . $msg, FILE_APPEND | LOCK_EX);
if(empty($requesterName)){
$requesterName = "Team";
}
if (in_array($update, array(0, 2, 3))) {
$mail_id = strstr($filename, '-', true);
$params = array(
'subject' => $msg,
'body' => "<p>Hi ".$requesterName.",<br/></p>
<p>The DCG pricing tool has failed to upload a price quote input request(attached here) . Request you to please review and correct the template.
</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<br/>DCG Pricing Team</p>",
);
if(!empty($requester_emailId)){
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com,'.$requester_emailId, language_default(), $params);
}else{
// drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
}
}
}
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-#.]/', '', $string); // Removes special chars.
}
?>
I'm facing really serious issue on live server this code works fine 2 days before but now its saying memory exhausted, i tried to increase memory but still not working. Can you please somebody help me.

Categories