Show unique array data in php using slim framework - php

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.

Related

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);

I cannot get the totals to output properly on the event list

I have events that I have that printout under the dates that they occur, but I need them to print with "Today + the date" or "Yesterday = the date" depending on if this is true or not.
$notes = UsersNote::where('user_id','=',$user_id)->get();
foreach($notes as $note) {
$activity = [];
$activity['icon'] = "/assets/icon-activity2-new-note.svg";
$activity['action'] = "New Note";
if($note->is_private > 0) {
$activity['icon'] = "/assets/icon-activity2-new-private-note.svg";
$activity['action'] = "New Private Note";
}
$activity['detail'] = $note->note;
if(!empty($note->author_id)) {
$author_name = UsersPermission::withTrashed()->where('user_id','=',$note->author_id)->value('name');
}
if(!empty($author_name)) $activity['detail'] = $author_name." wrote: ".$activity['detail'];
$activity['media'] = "";
$activity['link'] = "";
$activity['time'] = strtotime($note->created_at);
$activity['hourly'] = Format::shortTime($note->created_at);
$activity['since'] = Format::shortDate($note->created_at);
if($view == "all" && $note->is_private > 0) $activities[] = $activity;
else if($note->is_private == 0) $activities[] = $activity;
}
// Re-order by date
usort($activities, function ($a, $b) {
return ($b['time'] > $a['time']);
});
// Group
$new_activities = [];
foreach($activities as $activity) {
if(isset($new_activities[$activity['since']])) $new_activities[$activity['since']][] = $activity;
else $new_activities[$activity['since']] = [$activity];
$the_date=strtotime($activity['since']);
if($the_date = strtotime('today UTC')) {
"Today ".$the_date;
} elseif ($the_date = strtotime('yesterday UTC')) {
"Yesterday ".$the_date;
} else {
$the_date;
}
}
return response()->json(array_values($new_activities), 200);
Assuming $new_activities = []; is a Collection. (If it's an array collect($array) to turn it into collection).
You can utilize map() to add a field or override an existing field.
$activities->map(function($activity) {
$the_date = strtotime($activity['since']);
if($the_date == strtotime('today UTC')) {
$activity['formatted_date'] = "Today ". $the_date;
} elseif ($the_date == strtotime('yesterday UTC')) {
$activity['formatted_date'] = "Today ". $the_date;
} else {
$activity['formatted_date'] = $the_date;
}
return $activity;
})
Now check the result with dd($activities).

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.

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

Saving reservations using available 2 halls

Below is the function for saving some reservation details to the database. get_hall() query returns 2 halls(haal1 and hall2). bus when going to the database only hall1 is inserting. I want to insert hall1 next reservation hall2. How to improve below code.
function save_reserve_detail($date,$time,$flag){
$halls = $this->halls_model->get_hall();
foreach ($halls AS $each) {
$hall = $each['hall_id'];
break;
}
$reference_no = date("YmdHis");
if ($flag == 1) {
$hall_id = $hall;
$type = 1;
$date = $date;
} else if ($flag == 2) {
$hall_id = $hall;
$type = 0;
$date = $date;
}
$data = array(
'reference_no' => $reference_no,
'date' => $date,
'type' => $type,
'hall' => $hall
);
$result = $this->db->insert('reserving_details', $data);
if ($result) {
return $reference_no;
} else {
return 0;
}
}
Remove the break from foreach . now the $hall contains an array of 2 values. now use a for loop to insert the value into the table.
<?php
function save_reserve_detail($date,$time,$flag){
$halls = $this->halls_model->get_hall();
foreach ($halls AS $each) {
$hall = $each['hall_id'];
// break;
}
$reference_no = date("YmdHis");
if ($flag == 1) {
$hall_id = $hall;
$type = 1;
$date = $date;
} else if ($flag == 2) {
$hall_id = $hall;
$type = 0;
$date = $date;
}
for($i=0;$i<sizeof($hall);$i++){
$data = array(
'reference_no' => $reference_no,
'date' => $date,
'type' => $type,
'hall' => $hall[$i]
);
$result = $this->db->insert('reserving_details', $data);
if ($result) {
return $reference_no;
} else {
return 0;
}
}
}
?>
Even you can alter your insert('reserving_details', $data); code which can handle array insertion.

Categories