php foreach loop I am doing something wrong - php

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.

Related

CSGO Steam API ~ How to fetch both tradeable and non-tradeable items into array

My code is here:
case 'get_inv':
if(!$user) exit(json_encode(array('success'=>false, 'error'=>'You must login to access the deposit.')));
if((file_exists('cache/'.$user['steamid'].'.txt')) && (!isset($_GET['nocache']))) {
$array = file_get_contents('cache/'.$user['steamid'].'.txt');
$array = unserialize($array);
$array['fromcache'] = true;
if(isset($_COOKIE['tid'])) {
$sql = $db->query('SELECT * FROM `trades` WHERE `id` = '.$db->quote($_COOKIE['tid']).' AND `status` = 0');
if($sql->rowCount() != 0) {
$row = $sql->fetch();
$array['code'] = $row['code'];
$array['amount'] = $row['summa'];
$array['tid'] = $row['id'];
$array['bot'] = "Bot #".$row['bot_id'];
} else {
setcookie("tid", "", time() - 3600, '/');
}
}
exit(json_encode($array));
}
$prices = file_get_contents('prices.txt');
$prices = json_decode($prices, true);
$inv = file_get_contents('https://steamcommunity.com/profiles/'.$user['steamid'].'/inventory/json/730/2/');
$inv = json_decode($inv, true);
if($inv['success'] != 1) {
exit(json_encode(array('error'=>'Your profile is private. Please set your inventory to public and try again.')));
}
$items = array();
foreach ($inv['rgInventory'] as $key => $value) {
$id = $value['classid'].'_'.$value['instanceid'];
$trade = $inv['rgDescriptions'][$id]['tradable'];
if(!$trade) continue;
$name = $inv['rgDescriptions'][$id]['market_hash_name'];
$price = $prices['response']['items'][$name]['value']*0.9;
$img = 'http://steamcommunity-a.akamaihd.net/economy/image/'.$inv['rgDescriptions'][$id]['icon_url'];
if((preg_match('/(Souvenir)/', $name)) || ($price < $min)) {
$price = 0;
$reject = 'Junk';
} else {
$reject = 'unknown item';
}
$items[] = array(
'assetid' => $value['id'],
'bt_price' => "0.00",
'img' => $img,
'name' => $name,
'price' => $price,
'reject' => $reject,
'sa_price' => $price,
'steamid' => $user['steamid']);
}
$array = array(
'error' => 'none',
'fromcache' => false,
'items' => $items,
'success' => true);
if(isset($_COOKIE['tid'])) {
$sql = $db->query('SELECT * FROM `trades` WHERE `id` = '.$db->quote($_COOKIE['tid']).' AND `status` = 0');
if($sql->rowCount() != 0) {
$row = $sql->fetch();
$array['code'] = $row['code'];
$array['amount'] = $row['summa'];
$array['tid'] = $row['id'];
$array['bot'] = "Bot #".$row['bot_id'];
} else {
setcookie("tid", "", time() - 3600, '/');
}
}
file_put_contents('cache/'.$user['steamid'].'.txt', serialize($array), LOCK_EX);
exit(json_encode($array));
break;
I am trying to get people steam csgo inventory and put into an array. This works perfectly. Could someone help me figure out how to add a not tradeable tag. My plan is to add the item to the array even if not tradeable. I currently have it so if the item isnt worth < $0.30 then call it junk and ignore the press when clicked on. So something like if (!tradable) then mark as "trade locked" and ignore the press. Thank you.

Show unique array data in php using slim framework

I want to show to unique array value in PHP using Slim framework, but it shows same value multiple times. It fetch multiple same array according date. I run a SQLquery using group by date, where I get multiple date. For example: 04-01-2020,06-01-2020,07-01-2020.
In this example 04-01-2020 is in week between 29-12-2019 to 04-01-2020. But 06-01-2020,07-01-2020 are both between 05-01-2020 to 11-01-2020`. Show my array index show twice. I want it shows once in daterange array
My code:
public function Getkalyanchartdatewise()
{
$response = array();
$sql1 = "Select Date from matka_result WHERE matka_name_id=2 Group by Date ORDER BY `matka_result`.`date` ASC";
$stmt1 = $this->conn->prepare($sql1);
if ($stmt1) {
//$stmt1->bind_param ( "i", $id );
$stmt1->execute();
$stmt1->store_result();
$num_rows1 = $stmt1->num_rows;
if ($num_rows1 > 0) {
$stmt1->bind_result($date);
$i = 0;
while ($result = $stmt1->fetch()) {
//Our YYYY-MM-DD date string.
$date1 = $date;
//Get the day of the week using PHP's date function.
$dayOfWeek = date("l", strtotime($date1));
$previous_week = strtotime($date1);
$start_week = strtotime("last sunday midnight", $previous_week);
$end_week = strtotime("next saturday", $start_week);
$start_week = date("Y-m-d", $start_week);
$end_week = date("Y-m-d", $end_week);
//echo $start_week.' '.$end_week ;
$chart = $this->GetmatkaResultByDate($start_week, $end_week);
if ($date1 >= $start_week && $date1 <= $end_week) {
$daterange = $start_week . ' to ' . $end_week;
}
$date_list[$i] = array(
"date-range" => $daterange,
"start_week_date" => $start_week,
"end_week_date" => $end_week,
/*"date" => $date,
"week" => $dayOfWeek,*/
"chart_details" => $chart["chart_list"],
);
$i++;
}
$response ["error"] = false;
$response ["msg"] = "DATA_FOUND";
$response ["date_list"] = $date_list;
} else {
$response ["error"] = true;
$response ["msg"] = "DATA_NOT_EXIST";
$response ["date_list"] = "";
}
} else {
$response ["error"] = true;
$response ["msg"] = "QUERY_EXCEPTION";
}
return $response;
}
public function GetmatkaResultByDate($start_week, $end_week)
{
//public function Getkalyanchartdatewise(){
$response = array();
$sql1 = "Select `date`,`time1_result`,`time1_result_summation`,`time2_result`,`time2_result_summation` from matka_result WHERE matka_name_id=2 and Date between ? and ? ORDER BY `matka_result`.`date` ASC";
$stmt1 = $this->conn->prepare($sql1);
if ($stmt1) {
$stmt1->bind_param("ss", $start_week, $end_week);
$stmt1->execute();
$stmt1->store_result();
$num_rows1 = $stmt1->num_rows;
if ($num_rows1 > 0) {
$stmt1->bind_result($date, $time1_result, $time1_result_summation, $time2_result,
$time2_result_summation);
$i = 0;
while ($result = $stmt1->fetch()) {
$date1 = $date;
$dayOfWeek = date("l", strtotime($date1));
$chart_list[$i] = array(
"date" => $date,
"day" => $dayOfWeek,
"time1_result" => $time1_result,
"time1_result_summation" => $time1_result_summation,
"time2_result" => $time2_result,
"time2_result_summation" => $time2_result_summation,
);
$i++;
}
$response ["error"] = false;
$response ["msg"] = "DATA_FOUND";
$response ["chart_list"] = $chart_list;
} else {
$response ["error"] = true;
$response ["msg"] = "DATA_NOT_EXIST";
$response ["date_list"] = "";
}
} else {
$response ["error"] = true;
$response ["msg"] = "QUERY_EXCEPTION";
}
return $response;
}
My result output:
I want array 1 index not 2,3 which has same 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';
}
}
}

Unset Designer from variable

I am displaying product Id, product name , designer, but i need to hide "designer".
so i am trying to unset designer from variable $orderitems, i am trying below code, but still Designer column displaying
i am fetching product id , name , Designer from this code : ->addAttributeToSelect('dproduct_id') & trying this code to unset : unset($orderitems['designer_id'])
function getDesignerCollection()
{
$user_home = new USER();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetch(PDO::FETCH_ASSOC);
$accountType = $rows['type'];
if ($accountType == "admin")
{
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id', array(
'nin' => '0'
));
}
else
{
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id', array(
'like' => '%' . $_SESSION['userSession'] . '%'
))
->addAttributeToSelect('dproduct_id')
->addAttributeToSelect('state');
//unset($orderitems['designer_id']);
}
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
$oDate = new DateTime($orderData['created_at']);
$sDate = $oDate->format("Y-m-d");
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details WHERE designerorder_id=:designerorder_id");
$stmtorders->execute(array(
":designerorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$productdetail->getName() ,
$designerName,
$orderData['status'],
$orderData['grand_total'],
$orderData['customer_email'],
$commission,
$dorderStatus,
$sDate
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
unset($orderitems['designer_id']);
}
Note : I really tried lot before posting here, i am new to php.

mysql query and cookies

newbies should be encouraged. rather discouraging
I am new an having problems in understanding docs of php.
can someone give the exact code steps for my future reference to :
I want to run this query:
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
(I know it will return only one value) and 1. if "if tacking named cookie exists, delete it or replace it and set a cookie named "tracking" for one year with the value returned by that query. How can i do it?
I know little about php . but i get the feeling that i have no reference to db in that confirm.php . it doesnot extends model, nor i know would $this work here or not
the file iam working on is.
<?php
class ControllerCheckoutConfirm extends Controller {
public function index() {
$redirect = '';
if ($this->cart->hasShipping()) {
// Validate if shipping address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
if (empty($shipping_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if shipping method has been set.
if (!isset($this->session->data['shipping_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
} else {
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
// Validate if payment address has been set.
$this->load->model('account/address');
if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$payment_address = $this->session->data['guest']['payment'];
}
if (empty($payment_address)) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate if payment method has been set.
if (!isset($this->session->data['payment_method'])) {
$redirect = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$redirect = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$redirect = $this->url->link('checkout/cart');
break;
}
}
if (!$redirect) {
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
$this->load->model('setting/extension');
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
$this->language->load('checkout/checkout');
$data = array();
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = $this->config->get('config_name');
if ($data['store_id']) {
$data['store_url'] = $this->config->get('config_url');
} else {
$data['store_url'] = HTTP_SERVER;
}
if ($this->customer->isLogged()) {
$data['customer_id'] = $this->customer->getId();
$data['customer_group_id'] = $this->customer->getCustomerGroupId();
$data['firstname'] = $this->customer->getFirstName();
$data['lastname'] = $this->customer->getLastName();
$data['email'] = $this->customer->getEmail();
$data['telephone'] = $this->customer->getTelephone();
$data['fax'] = $this->customer->getFax();
$this->load->model('account/address');
$payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
} elseif (isset($this->session->data['guest'])) {
$data['customer_id'] = 0;
$data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
$data['firstname'] = $this->session->data['guest']['firstname'];
$data['lastname'] = $this->session->data['guest']['lastname'];
$data['email'] = $this->session->data['guest']['email'];
$data['telephone'] = $this->session->data['guest']['telephone'];
$data['fax'] = $this->session->data['guest']['fax'];
$payment_address = $this->session->data['guest']['payment'];
}
$data['payment_firstname'] = $payment_address['firstname'];
$data['payment_lastname'] = $payment_address['lastname'];
$data['payment_company'] = $payment_address['company'];
$data['payment_company_id'] = $payment_address['company_id'];
$data['payment_tax_id'] = $payment_address['tax_id'];
$data['payment_address_1'] = $payment_address['address_1'];
$data['payment_address_2'] = $payment_address['address_2'];
$data['payment_city'] = $payment_address['city'];
$data['payment_postcode'] = $payment_address['postcode'];
$data['payment_zone'] = $payment_address['zone'];
$data['payment_zone_id'] = $payment_address['zone_id'];
$data['payment_country'] = $payment_address['country'];
$data['payment_country_id'] = $payment_address['country_id'];
$data['payment_address_format'] = $payment_address['address_format'];
if (isset($this->session->data['payment_method']['title'])) {
$data['payment_method'] = $this->session->data['payment_method']['title'];
} else {
$data['payment_method'] = '';
}
if (isset($this->session->data['payment_method']['code'])) {
$data['payment_code'] = $this->session->data['payment_method']['code'];
} else {
$data['payment_code'] = '';
}
if ($this->cart->hasShipping()) {
if ($this->customer->isLogged()) {
$this->load->model('account/address');
$shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
} elseif (isset($this->session->data['guest'])) {
$shipping_address = $this->session->data['guest']['shipping'];
}
$data['shipping_firstname'] = $shipping_address['firstname'];
$data['shipping_lastname'] = $shipping_address['lastname'];
$data['shipping_company'] = $shipping_address['company'];
$data['shipping_address_1'] = $shipping_address['address_1'];
$data['shipping_address_2'] = $shipping_address['address_2'];
$data['shipping_city'] = $shipping_address['city'];
$data['shipping_postcode'] = $shipping_address['postcode'];
$data['shipping_zone'] = $shipping_address['zone'];
$data['shipping_zone_id'] = $shipping_address['zone_id'];
$data['shipping_country'] = $shipping_address['country'];
$data['shipping_country_id'] = $shipping_address['country_id'];
$data['shipping_address_format'] = $shipping_address['address_format'];
if (isset($this->session->data['shipping_method']['title'])) {
$data['shipping_method'] = $this->session->data['shipping_method']['title'];
} else {
$data['shipping_method'] = '';
}
if (isset($this->session->data['shipping_method']['code'])) {
$data['shipping_code'] = $this->session->data['shipping_method']['code'];
} else {
$data['shipping_code'] = '';
}
} else {
$data['shipping_firstname'] = '';
$data['shipping_lastname'] = '';
$data['shipping_company'] = '';
$data['shipping_address_1'] = '';
$data['shipping_address_2'] = '';
$data['shipping_city'] = '';
$data['shipping_postcode'] = '';
$data['shipping_zone'] = '';
$data['shipping_zone_id'] = '';
$data['shipping_country'] = '';
$data['shipping_country_id'] = '';
$data['shipping_address_format'] = '';
$data['shipping_method'] = '';
$data['shipping_code'] = '';
}
$product_data = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$value = $this->encryption->decrypt($option['option_value']);
}
$option_data[] = array(
'product_option_id' => $option['product_option_id'],
'product_option_value_id' => $option['product_option_value_id'],
'option_id' => $option['option_id'],
'option_value_id' => $option['option_value_id'],
'name' => $option['name'],
'value' => $value,
'type' => $option['type']
);
}
$product_data[] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'download' => $product['download'],
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $product['price'],
'total' => $product['total'],
'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
'reward' => $product['reward']
);
}
// Gift Voucher
$voucher_data = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$voucher_data[] = array(
'description' => $voucher['description'],
'code' => substr(md5(mt_rand()), 0, 10),
'to_name' => $voucher['to_name'],
'to_email' => $voucher['to_email'],
'from_name' => $voucher['from_name'],
'from_email' => $voucher['from_email'],
'voucher_theme_id' => $voucher['voucher_theme_id'],
'message' => $voucher['message'],
'amount' => $voucher['amount']
);
}
}
$data['products'] = $product_data;
$data['vouchers'] = $voucher_data;
$data['totals'] = $total_data;
$data['comment'] = $this->session->data['comment'];
$data['total'] = $total;
$query = $this->db->query("SELECT affiliate_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
//set cookie $query->rows;
if (isset($this->request->cookie['tracking'])) {
$this->load->model('affiliate/affiliate');
$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
$subtotal = $this->cart->getSubTotal();
if ($affiliate_info) {
$data['affiliate_id'] = $affiliate_info['affiliate_id'];
$data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
} else {
$data['affiliate_id'] = 0;
$data['commission'] = 0;
}
$data['language_id'] = $this->config->get('config_language_id');
$data['currency_id'] = $this->currency->getId();
$data['currency_code'] = $this->currency->getCode();
$data['currency_value'] = $this->currency->getValue($this->currency->getCode());
$data['ip'] = $this->request->server['REMOTE_ADDR'];
if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
} elseif(!empty($this->request->server['HTTP_CLIENT_IP'])) {
$data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
} else {
$data['forwarded_ip'] = '';
}
if (isset($this->request->server['HTTP_USER_AGENT'])) {
$data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
} else {
$data['user_agent'] = '';
}
if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
} else {
$data['accept_language'] = '';
}
$this->load->model('checkout/order');
$this->session->data['order_id'] = $this->model_checkout_order->addOrder($data);
$this->data['column_name'] = $this->language->get('column_name');
$this->data['column_model'] = $this->language->get('column_model');
$this->data['column_quantity'] = $this->language->get('column_quantity');
$this->data['column_price'] = $this->language->get('column_price');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['products'] = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$filename = $this->encryption->decrypt($option['option_value']);
$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$this->data['products'][] = array(
'product_id' => $product['product_id'],
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'subtract' => $product['subtract'],
'price' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))),
'total' => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']),
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
);
}
// Gift Voucher
$this->data['vouchers'] = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$this->data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'])
);
}
}
$this->data['totals'] = $total_data;
$this->data['payment'] = $this->getChild('payment/' . $this->session->data['payment_method']['code']);
} else {
$this->data['redirect'] = $redirect;
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/confirm.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/confirm.tpl';
} else {
$this->template = 'default/template/checkout/confirm.tpl';
}
$this->response->setOutput($this->render());
}
}
?>
It can be done this way .
<?php
$query = $this->db->query("SELECT tracking_code FROM " . DB_PREFIX . "customer WHERE language_id = '" . (int)$this->customer->getId() . "'");
if(isset($_COOKIE['tracking'])){
setcookie('tracking', '', time()-1);
sleep(1); // sleep for 1 sec
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}else{
setcookie('tracking', '$query->row["tracking_code"]', time()+60*60*24*30*12);
}
?>
So in the if condition ,if your cookie named tracking is set than it will delete it with 1 sec and and apply you new value from $query . I hope this will work .

Categories