Unable to maintain Session in Laravel - php

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';
}
}
}

Related

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.

Does not display the result of parsing

Good afternoon, please help me. At me when parsing the result of parsing is not displayed.
link my php file https://dropmefiles.com/cv4Q2
Please correct where I was wrong. Or help to rewrite a little code so that it displays the result of the parser.
Already tried all the options, it does not work in any way. My knowledge here is not enough.
1 file
part 1
function getForecastXML($cid='579432') {
$cid = "579432";
$hoffset = "4";
$appid= "d86ad74d22ce9cc528d8baee65acd408";
$lang= "ru";
$days = array();
$xml = #file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=$cid&mode=xml&appid=$appid&lang=$lang&type=like");
if ($xml===false) { return;} else {
$xml = simplexml_load_string($xml);
$cityname = (string)$xml->location->name;
$weekdays[0] = "Воскресенье";
$weekdays[1] = "Понедельник";
$weekdays[2] = "Вторник";
$weekdays[3] = "Среда";
$weekdays[4] = "Четверг";
$weekdays[5] = "Пятница";
$weekdays[6] = "Суббота";
if (count($xml->forecast->time)>0){
foreach ($xml->forecast->time as $fpart) {
$forecast = array();
$attr = $fpart->attributes();
$forecast['t']['min'] = (string)round(($fpart->temperature->attributes()->min)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['min'] = $forecast['t']['min'] > 0 ? "+".$forecast['t']['min'] : $forecast['t']['min'];
$forecast['t']['max'] = (string)round(($fpart->temperature->attributes()->max)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['max'] = $forecast['t']['max'] > 0 ? "+".$forecast['t']['max'] : $forecast['t']['max'];
$forecast['p']['min'] = (string)round($fpart->pressure->attributes()->value,0,PHP_ROUND_HALF_UP);
// $forecast['p']['max'] = (string)$fpart->PRESSURE->attributes()->max;
$forecast['w']['min'] = (string)round($fpart->windSpeed->attributes()->mps,0,PHP_ROUND_HALF_UP);
//$forecast['w']['max'] = (string)$fpart->WIND->attributes()->max;
//$forecast['w']['rumb'] = (string)$fpart->WIND->attributes()->direction;
$forecast['h']['min'] = (string)$fpart->humidity->attributes()->value;
//$forecast['h']['max'] = (string)$fpart->RELWET->attributes()->max;
$forecast['symb'] = (string)$fpart->symbol->attributes()->name;
$forecast['pict'] = (string)$fpart->symbol->attributes()->var;
$date = date('c',strtotime($hoffset.' hours',strtotime($attr['from'])));
$hour = date('H',strtotime($date));
$forecast['timestamp'] =strtotime($date);
$date = strtotime($date);
$dayofweek = date('w',$date);
$date = $weekdays[$dayofweek]." ".date('d.m',$date);
if ($forecast['timestamp'] > time()){
$days[$date][$hour] = $forecast;
}
}
} else {$days=array();}
}
//return array($cityname,$days);
return [$cityname => $days];
//echo [$cityname => $days];
}
part 2
$outputData = array();
if (count($this->forecast) > 0) {
foreach ($this->forecast as $date => $daypart) {
$outputData[] = $date;
foreach ($daypart as $dp => $data) {
$outputData[] = str_pad($dp, 2, '0', STR_PAD_LEFT);
$outputData[] = $data['symb'];
$outputData[] = $data['t']['min'];
$outputData[] = $data['t']['max'];
if (($data['p']['min']) > 0) {
$outputData[] = "Давление " . round($data['p']['min'] * 0.75006375541921) . "мм. рт. ст.";
}
}
}
} else {
$outputData[] = "В данный момент информация о погоде отсутствует";
}
echo implode(' ', $outputData);

php foreach loop I am doing something wrong

Like for example, I have the following code
if ($result == 1) {
foreach ($records as $record) {
$request_date = $record['date'];
$request_starttime = $record['start_time'];
echo $request_date . " " . $request_starttime;
}
throw new UserException("Unfortunately, this slot is already booked,please check another slot");
} else {
//do something else
}
Here exception is showing fine, but the echo code before that in the block is not displaying on the page.
How I can achieve this?
The result of print_r($slots)
Array
(
[0] => 2018-12-12 12:45:00
)
Array
(
[0] => 2018-12-12 12:45:00
[1] => 2018-12-12 13:00:00
)
Array
(
[0] => 2018-12-12 12:45:00
[1] => 2018-12-12 13:00:00
[2] => 2018-12-12 13:15:00
)
Array
(
[0] => 2018-12-12 12:45:00
[1] => 2018-12-12 13:00:00
[2] => 2018-12-12 13:15:00
[3] => 2018-12-12 13:30:00
)
I have added the print_r($slots) just before the throw new userException line.
The more detailed code block is like this:
foreach ($order_item as $key => $value) {
$order = new OrderItem();
$class_info = ClassDuration::find()->where(['id' => $value['id']])->one();
$end_date = date('Y-m-d', strtotime($model->create_date));
//$p_price = $value['price'];
$order->cd_id = $value['id'];
$order->user_id = $UserId;
$order->location_id = $value['location_id'];
$order->instructor_id = $value['instructor_id'];
$order->date = $value['date1'];
$order->start_time = $value['starttime'];
$order->end_time = date("h:i",strtotime($value['endtime']));
//$order->price = $p_price * $value['q'];
$order->order_id = $model->id;
$instructor=$value['instructor_id'];
$date=$value['date1'];
$starttime =$value['starttime'];
$query = Yii::$app->db->createCommand("SELECT IF(EXISTS(SELECT * FROM `order_item` WHERE `instructor_id`='$instructor' and `date` = '$date' AND `start_time` = '$starttime'), 1, 0)");
$query1 = Yii::$app->db->createCommand("SELECT * FROM `order_item` WHERE exists(select * FROM dual where `instructor_id`='$instructor' and `date` = '$date' AND `start_time` = '$starttime')");
$records=$query1->queryAll();
$result=$query->queryScalar();
//var_dump($result);exit;
if ($result == 1) {
foreach ($records as $record) {
$request_date = $record['date'];
$request_starttime = $record['start_time'];
$slots[] = $request_date . " " . $request_starttime;
}
print_r($slots);
$userMessage = "Unfortunately, this slot is already booked,please check another slot." . implode("<br />", $slots);
//throw new UserException($userMessage);
//echo $userMessage;
}else{
//$order->save();
}
// $grand_total = $grand_total + $order->price;
$ttl_dis = $ttl_dis;
}
You are trying to list the slots that are retrieved as already booked by another user inside $records, as the part of the text that you are showing in the exception, if that is correct then the exception will not allow you to show any other text except the one mentioned inside the exception message you should append the text with the exception message and then you can display it along with the message.
if ($result == 1) {
foreach ($records as $record) {
$request_date = $record['date'];
$request_starttime = $record['start_time'];
$slots[] = $request_date . " " . $request_starttime;
}
$userMessage = "Unfortunately, this slot is already booked,please check another slot." . implode("<br />", $slots);
throw new UserException($userMessage);
} else {
//do something else
}
Update
you should check for the slots before you save anything in the model and redirect to the view see the below code i added an extra function to checkSlots()
public function actionCheckout() {
if( Yii::$app->user->isGuest ){
return $this->redirect(['/site/login-popup']);
}
$session = Yii::$app->session;
$model = new Order();
//$profile = UserProfile::findOne(24);//(['id' => 27])->all();//->where(['id'=>Yii::$app->user->identity->id])->one();
$user = User::findOne(['id' => Yii::$app->user->identity->id]);
$profile = UserProfile::findOne(['user_id' => Yii::$app->user->identity->id]);
$billinginfo = UserBillingInfo::findOne(['user_id' => Yii::$app->user->identity->id]);
$userchildren = UserChildren::findOne(['user_id' => Yii::$app->user->identity->id]);
$modelsKids = $user->kids;
//var_dump($modelsKids);exit;
//Customer::findOne(10);
// var_dump($profile->zipcode);exit;
$model->status = "unpaid";
$model->first_name = Yii::$app->user->identity->first_name;
$model->last_name = Yii::$app->user->identity->last_name;
$model->mobile = Yii::$app->user->identity->phone;
$model->email = Yii::$app->user->identity->email;
$model->address = isset($profile->street1) ? $profile->street1 : '';
$model->city = isset($profile->city) ? $profile->city : '';
$model->state = isset($profile->state) ? $profile->state : '';
$model->post_code = isset($profile->zipcode) ? $profile->zipcode : '';
$pp = new PaypalPayment();
$st = Yii::$app->getTable;
$site_name = $st->settings('general', 'site_name');
if( Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) ){
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
//$order_item = \Yii::$app->getRequest()->getCookies()->getValue('order_item');
$order_item = $session['value'];
if( count($order_item) <= 0 ){
return $this->goHome();
}
$total = 0;
for( $x = 0; $x < count($order_item); $x++ ){
// $cart_p_p = $order_item[$x]['price'];
// $total = $total + $cart_p_p * $order_item[$x]['q'];
}
if( Yii::$app->user->isGuest ){
return $this->render('checkout', [
'model' => $model,
]);
}
$UserId = Yii::$app->user->identity->id;
//check if all slots are available
$allSlotsAvailable = $this->checkSlots($order_item);
if( $model->load(Yii::$app->request->post()) && $allSlotsAvailable ){
$user = User::findOne(['id' => Yii::$app->user->identity->id]);
$profile = UserProfile::findOne(['user_id' => $user]);
if( !empty($UserProfile) ){
$profile = UserProfile::findOne(['user_id' => $user]);
} else{
$profile = new UserProfile();
}
$model->order_number = date('ymdhis');
$model->create_date = date('Y-m-d H:i:s');
$model->status = 1;
$model->create_by = $UserId;
// $model->order_amount = $total;
//var_dump($_REQUEST);
$user->phone = $_REQUEST['Order']['mobile'];
$user->first_name = $_REQUEST['Order']['first_name'];
$user->last_name = $_REQUEST['Order']['last_name'];
$profile->user_id = $user->id;
$profile->mobile = $_REQUEST['Order']['mobile'];
$profile->street1 = $_REQUEST['Order']['address'];
$profile->city = $_REQUEST['Order']['city'];
$profile->state = $_REQUEST['Order']['state'];
$profile->zipcode = $_REQUEST['Order']['post_code'];
$profile->save(false);
if( !empty($_REQUEST['Order']['kids']) ){
$model->kids = serialize($_REQUEST['Order']['kids']);
}
$model->save();
$user->save();
$model->orderUpdate($model->id, 1, NULL);
$grand_total = 0;
$ttl_dis = 0;
foreach( $order_item as $key => $value ){
$order = new OrderItem();
$class_info = ClassDuration::find()->where(['id' => $value['id']])->one();
$end_date = date('Y-m-d', strtotime($model->create_date));
//$p_price = $value['price'];
$order->cd_id = $value['id'];
$order->user_id = $UserId;
$order->location_id = $value['location_id'];
$order->instructor_id = $value['instructor_id'];
$order->date = $value['date1'];
$order->start_time = $value['starttime'];
$order->end_time = date("h:i", strtotime($value['endtime']));
//$order->price = $p_price * $value['q'];
$order->order_id = $model->id;
$order->save();
// $grand_total = $grand_total + $order->price;
$ttl_dis = $ttl_dis;
}
$model->order_amount = $grand_total;
$model->save();
$session->remove('date1');
$session->remove('time1');
Yii::$app->session->setFlash('orderPlaced');
$link = '#';
if( $model->payment_method == 'paypal' ){
$new_array = $order_item;
$pp->addMultipleItems($new_array);
return $pp->getCheckoutForm($model->id);
} elseif( $model->payment_method == 'invoice' ){
$content = $this->renderPartial('_invoice', ['model' => $model]);
//var_dump($content);
$filename = 'web/customer-invoice/invoice' . $model->id . '.pdf';
$pdf = new Pdf(['format' => Pdf::FORMAT_A4]);
$mpdf = $pdf->api;
$stylesheet = file_get_contents('themes/common/css/print/invoice.css');
$mpdf->WriteHTML($stylesheet, 1);
$mpdf->WriteHtml($content);
$mpdf->Output($filename, 'F');
$from_email = $st->settings('email', 'from_email');
$from_name = $st->settings('email', 'from_name');
$user = User::findOne($UserId);
$to = $user['email'];
$email_template = $st->email_template(10);
\Yii::$app->mailer->compose('template', ['id' => 10, 'user_id' => $UserId,
'email_template' => $email_template,
'model' => $model,
'link' => $link])
->setFrom([$from_email => $from_name])
->setTo($to)
->setSubject($email_template['subject'] . ' ' . $site_name)
->attach($filename)
->send();
} elseif( $model->payment_method == 'booking' ){
$admin = User::find()->select('email')->where(['user_role' => 'admin'])->asArray()->all();
$admin = ArrayHelper::getColumn($admin, 'email');
$content = $this->renderPartial('_booking', ['model' => $model]);
// var_dump($content);
$filename = 'web/customer-booking/booking' . $model->id . '.pdf';
$pdf = new Pdf(['format' => Pdf::FORMAT_A4]);
$mpdf = $pdf->api;
$stylesheet = file_get_contents('themes/common/css/print/invoice.css');
$mpdf->WriteHTML($stylesheet, 1);
$mpdf->WriteHtml($content);
$mpdf->Output($filename, 'F');
$from_email = $st->settings('email', 'from_email');
$from_name = $st->settings('email', 'from_name');
$user = User::findOne($UserId);
$orderid = Order::find(['created_by' => $user->id])->select('id')->orderBy('create_date DESC')->one();
$instructor_id = OrderItem::find()->select('instructor_id')->where(['order_id' => $orderid])->distinct();
$Instructor = User::findOne($instructor_id);
// var_dump($instructor_id);exit;
// $admin = ArrayHelper::getColumn($admin, 'email');
$to = $user['email'];
$instructor_email = $Instructor['email'];
$admin[] = $to;
$admin[] = $instructor_email;
// $to .= $Instructor['email'];
$email_template = $st->email_template(10);
\Yii::$app->mailer->compose('template', ['id' => 10, 'user_id' => $UserId,
'email_template' => $email_template,
'model' => $model,
'link' => $link])
->setFrom([$from_email => $from_name])
->setTo($admin)
->setSubject($email_template['subject'] . ' ' . $site_name)
->attach($filename)
->send();
}
//Yii::$app->response->cookies->remove('order_item');
unset($session['value']);
return $this->redirect(Yii::getAlias('#web') . '/order/view?id=' . $model->id);
//return $this->redirect('result');
} else{
return $this->render('checkout', [
'model' => $model,
// 'modelsKids' => (empty($modelsKids)) ? [new UserChildren] : $modelsKids,
]);
}
}
private function checkSlots($order_items) {
$slots = [];
foreach( $order_items as $item ){
$instructor = $item['instructor_id'];
$date = $item['date1'];
$starttime = $item['starttime'];
$query = Yii::$app->db->createCommand("SELECT IF(EXISTS(SELECT * FROM `order_item` WHERE `instructor_id`='$instructor' and `date` = '$date' AND `start_time` = '$starttime'), 1, 0)");
$result = $query->queryScalar();
if( $result == 1 ){
$slots[] = $date . " " . $starttime;
}
}
if( sizeof($slots) ){
Yii::$app->session->setFlash('error', "Unfortunately, this slot is already booked,please check another slot<br />".implode("<br />", $slots));
return false;
} else{
return true;
}
}
in the function checkSlots($order_items) you will see that I have removed one of your queries
$query1 = Yii::$app->db->createCommand("SELECT * FROM `order_item` WHERE exists(select * FROM dual where `instructor_id`='$instructor' and `date` = '$date' AND `start_time` = '$starttime')");
as its un-necessary to retrieve the records for the same date and start_time that you are querying with, and just use the result from the first query and add the date and start time to the $slots and once all records are checked and if there are any reserved slots the method returns false and the view will be displayed along with the flash message that will show all those slots that are reserved.

Can't set new product's quantity and supplier from a prestashop module

I write a prestashop module which allows adding new products. I have a problem: in table 'ps_products' it saves all the information with success but when I open added product in admin panel catalog-> products, the quantity is 0 and no supplier is selected. Here is my code:
$message = '';
$erori = false;
$arr = array();
$feats = array();
$imgs = array();
$arr['nume_produs'] = Tools::getValue('pr_name');
$arr['pr_pret_ach'] = Tools::getValue('pr_pret_ach');
$arr['pr_pret_angro'] = Tools::getValue('pr_pret_angro');
$arr['pr_supp'] = explode("=", Tools::getValue('pr_supp'));
$arr['pr_refer'] = Tools::getValue('pr_refer');
$arr['pr_manuf'] = Tools::getValue('pr_manuf');
$arr['pr_short_desc'] = Tools::getValue('pr_short_desc');
$arr['proxy'] = Tools::getValue('proxy');
$res = yamarketsync::update_proxy($arr['proxy']);
$arr['categorii'] = Tools::getValue('categoryBox');
if(Tools::getValue('active') == 1) $arr['activ'] = true;
else $arr['activ'] = false;
$product = new Product();
$langId = (int) (Configuration::get('PS_LANG_DEFAULT'));
$name_ro = Tools::getValue('pr_name_ro');
if(Tools::getValue('pr_name_ru') != '')$name_ru = Tools::getValue('pr_name_ru'); else $name_ru = $name_ro;
if(Tools::getValue('pr_name_en') != '')$name_en = Tools::getValue('pr_name_en'); else $name_en = $name_ro;
if(Tools::getValue('pr_name_uk') != '')$name_uk = Tools::getValue('pr_name_uk'); else $name_uk = $name_ro;
$s_desc_ro = Tools::getValue('pr_short_desc_ro');
if(Tools::getValue('pr_short_desc_ru') != '')$s_desc_ru = Tools::getValue('pr_short_desc_ru'); else $s_desc_ru = $s_desc_ro;
if(Tools::getValue('pr_short_desc_en') != '')$s_desc_en = Tools::getValue('pr_short_desc_en'); else $s_desc_en = $s_desc_ro;
if(Tools::getValue('pr_short_desc_uk') != '')$s_desc_uk = Tools::getValue('pr_short_desc_uk'); else $s_desc_uk = $s_desc_ro;
$desc_ro = Tools::getValue('pr_desc_ro');
if(Tools::getValue('pr_desc_ru') != '')$desc_ru = Tools::getValue('pr_desc_ru'); else $desc_ru = $desc_ro;
if(Tools::getValue('pr_desc_en') != '')$desc_en = Tools::getValue('pr_desc_en'); else $desc_en = $desc_ro;
if(Tools::getValue('pr_desc_uk') != '')$desc_uk = Tools::getValue('pr_desc_uk'); else $desc_uk = $desc_ro;
$product->id_supplier = $arr['pr_supp'][0];
$product->supplier_name = $arr['pr_supp'][1];
$product->id_manufacturer = Tools::getValue('pr_manuf');
$product->description_short = array('4' => $s_desc_ro, '3' => $s_desc_ru, '1' => $s_desc_en,'5' => $s_desc_uk);
$product->description = array('4' => $desc_ro, '3' => $desc_ru, '1' => $desc_en,'5' => $desc_uk);
$product->quantity = Tools::getValue('pr_cant');
$product->name = array('4' => $name_ro, '3' => $name_ru, '1' => $name_en,'5' => $name_uk);
$product->price = Tools::getValue('pr_pret_ach');
$product->wholesale_price = Tools::getValue('pr_pret_angro');
$product->active = $arr['activ'];
$product->id_category_default= $arr['categorii'][0];
$product->category=$arr['categorii'];
$product->reference = $arr['pr_refer'];
$product->link_rewrite = array('4' => Tools::link_rewrite($name_ro),'3' => Tools::link_rewrite($name_ru),'1' => Tools::link_rewrite($name_en),'5' => Tools::link_rewrite($name_uk));
$res = $product->add();
if(!$res) $erori = true;
//adaugam features
$num = Tools::getValue('feat_num');
$i=0;
$id_product = (int)$product->id;
while($i <= $num){
if( Tools::getValue('feat_name-'.$i) !='' && Tools::getValue('feat_value-'.$i) != ''){
if(!yamarketsync::exista_deja_asociere(Tools::getValue('ya_feature_name-'.$i), Tools::getValue('feat_name-'.$i) )){
yamarketsync::save_asociere(Tools::getValue('ya_feature_name-'.$i), Tools::getValue('feat_name-'.$i) );
}
$rezultat = Product::addFeatureProductImport($id_product, Tools::getValue('feat_name-'.$i), Tools::getValue('feat_value-'.$i));
if(!$rezultat) $erori = true;
}
$feats[$i]['name'] = Tools::getValue('feat_name-'.$i);
$feats[$i]['value'] = Tools::getValue('feat_value-'.$i);
$i++;
}
$i=0;
$num = Tools::getValue('img_num');
while($i < $num){
$imgs[$i] = Tools::getValue('image-'.$i);
$img = new Image();
$img->id_product = $product->id;
$img->add();
$rezultat = AdminImportController::copyImg2($product->id, $img->id, $imgs[$i]);
if(!$rezultat) $erori = true;
$i++;
}
if($erori == true) return $this->displayError($this->l('Au aparut erori in timpul salvarii.'));
else return $this->displayConfirmation($this->l('Modificarile au fost salvate.'));
My friend, add this to complete update product quantity:
StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, $this->context->shop->id)

How to split and count sms messages from file in PHP

I have problem that my sms messages are imported with csv, then it is checked if number is ok and how long sms is. My problem is that if text messages is longer then 160 it still enters 1 in databse. But it should start counting, if it is less or equal than 160, it is 1 messages, if it is more than 160 but less or equal than 320 it is two messages and if it is more then it is 3 messages.
Page code is here:
<?php
$link = #mysql_connect("localhost", "admin", "") or die("Error: Database offline.");
mysql_select_db("database", $link);
mysql_query("SET NAMES 'utf8' ", $link);
function detect_type($smstext) {
$type = 0;
$dec_codes = array();
for ($i = 0; $i < strlen($smstext); $i++) {
$symbol = substr($smstext,$i,1);
if (!in_array(ord($symbol), $dec_codes)) { $type = 1; }
}
return $type;
}
$result_array = array();
$unic_numbers = array();
$fp = file_get_contents($_FILES['filename']['tmp_name']);
$fp = str_replace("\r\n", "\n", $fp);
$fp = str_replace("\r", "\n", $fp);
$fp = str_replace("\t", "", $fp);
$rows = explode("\n", $fp);
$imported_rows = 0;
$duplicate_rows = 0;
$error_rows = 0;
$long_rows = 0;
for ($i = 0; $i < sizeof($rows); $i++) {
$data = explode(";", $rows[$i]);
$data[1] = sms_formatNumbers($data[1]); // formating number
$userid = 78;
if(strlen($data[1]) > 9){
if($unic_numbers[$data[1]] != true ){ // unic number check
$unic_numbers[$data[1]] = true;
$imported_rows++;
$fullSMS = iconv("ISO-8859-1","UTF-8", trim($data[2])." ".trim($data[3])." ".trim($data[4]));
if(strlen($fullSMS) > 164){
$long_rows++;
}
if($_POST['action'] == 'send'){
// SMS TEXT
$smstext = str_replace("õ", "ò", $fullSMS);
$smstext = str_replace("Õ", "ò", $smstext);
$type = detect_type($smstext);
// servicegroup
$char2 = substr($data[1], 0, 2);
$char3 = substr($data[1], 0, 3);
$c1 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char2."'", $link);
$c2 = mysql_query("SELECT * FROM zone_info WHERE country_code = '".$char3."'", $link);
if (mysql_num_rows($c1) == 1) {
$r = mysql_fetch_array($c1);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
} else if (mysql_num_rows($c2) == 1) {
$r = mysql_fetch_array($c2);
$price = $r['price'];
$z = mysql_query("SELECT * FROM zone WHERE id = ".$r['up']."", $link);
$zone = mysql_fetch_array($z);
$zone_id = $zone['id'];
$servicegroup = $zone['servicegroup'];
}
require_once("../scripts/number.class.php");
$receiver = "00".$data[1];
$obj = new NumberClass($receiver);
$operator = $obj -> operator_code;
$country = $obj -> code;
$operator_name = $obj -> operator_name;
if(strlen($operator) > 0) {
$er = mysql_query("SELECT * FROM zone_exception WHERE country = ".$country." AND operator = ".$operator."", $link);
if (mysql_num_rows($er) == 1) {
$erand = mysql_fetch_array($er);
$price = $erand['price'];
$servicegroup = $erand['servicegroup'];
}
} else $operator_name = "-";
if ($operator_name == "-") { $servicegroup = $servicegroup; }
else {
if ($operator_name == " First Operator") $servicegroup = "90";
else if ($operator_name == "Second Operator") $servicegroup = "91";
else if ($operator_name == "Third Operator") $servicegroup = "92";
else $servicegroup = $servicegroup;
}
require_once("../core/init.mini.inc.php");
$servicegroup = UserBasedRerouting($receiver, $userid, $operator_name, $servicegroup);
$client_type ='corporative';
$sender = $data[0];
$zone_id = 11;
$client_sms_id = '0';
$client_want_report = '0';
$client_report_url = '';
$amount = 1;
$dt_delaysend = '1970-01-01 00:00:00';
$SMSsent = 0;
$SMStotal = 1;
$smstext_old = $smstext;
while($SMSsent < $SMStotal){
$sql = mysql_query("insert into sms_queue (user_id,client_type,dt_entered,sender,receiver,operator,smstext,sms_type,zone_id,client_sms_id,client_want_report,client_report_url,sms_price,amount,servicegroup,dt_delaysend) values ('$userid','$client_type','".date('Y-m-d H:i:s')."','$sender','$receiver','$operator_name','$smstext',0,'$zone_id','$client_sms_id','$client_want_report','$client_report_url','$price','$amount','$servicegroup','$dt_delaysend')", $link);
$SMSsent++;
}
}
}else{
$duplicate_rows ++;
}
}else{
$error_rows++;
}
}
$result_array['success'] = true;
$result_array['long_sms'] = $long_rows;
$result_array['send_sms'] = $imported_rows;
$result_array['error_sms'] = $error_rows;
$result_array['duplicate_sms'] = $duplicate_rows;
$result_array['action'] = $_POST['action'];
echo json_encode($result_array);
function sms_formatNumbers($number){
$number = (int)$number;
$start_code = (int)substr($number,0,4);
if($start_code < 3780 or $start_code == 3785 or $start_code > 3789){
return $number;
}else{
return '';
}
}
?>
Can someone help me out with that?
Thank you
Try
if(strlen($fullSMS) > 164){
$long_rows = ceil(strlen($fullSMS)/160);
}
instead of
if(strlen($fullSMS) > 164){
$long_rows++;
}

Categories