How to increase the performance of this function - php

How to increase the performance of following function in phalcon framework. There are thousands of records in the table. I tried different ways, but I am stuck the point. How can I increase the efficiency and reduce the execution time. Following are two methods:
public function currentmonthAction()
{
$payload = $this->request->getJsonRawBody();
$this->setDB();
$ticketsmodel = new Tickets();
$fromcitycondition = "";
if( isset($payload->city->id) )
{
$fromcitycondition = "and fromcity='{$payload->city->id}'";
}
try{
$date = new \Datetime($payload->date);
$year = $date->format('Y');
$month = $date->format('m');
$month = '08';
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
/* result for all cities passenger */
$result = array();
// get all cities permutations
$tmpcitiesdata = array();
$rawresultset = Tickets::find (
array(
'columns' => 'fromcity,tocity',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) ". $fromcitycondition,
'group' => 'fromcity,tocity'
));
foreach ($rawresultset as $rawresult) {
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['fromcity'] = $rawresult->fromcity;
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['tocity'] = $rawresult->tocity;
}
//var_dump($rawresultset);
// get tickets sold based on cities combinations
$total = 0;
foreach ($tmpcitiesdata as $tmpcities) {
$rawresultset = Tickets::find (
array(
'columns' => 'customer',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity'],
'group' => 'customer'
));
$totalsoldRaw = count($rawresultset);
// get ticket cancellations
$rawresultset = Tickets::find (
array(
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (3) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity']
));
//make sure cancellations are tickets cancellations not booking cancellations
foreach($rawresultset as $rawresult)
{
$resultNumber = Tickets::find("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
if( count($resultNumber) > 0 ){
$totalsoldRaw = $totalsoldRaw-1;
}
}
$total += $totalsoldRaw;
array_push($result, array('total' => $totalsoldRaw, 'fromcity' => Cities::findFirstById($tmpcities['fromcity'])->name, 'tocity' => Cities::findFirstById($tmpcities['tocity'])->name));
}
//sort result based on counts
arsort($result);
//cut result to max 6 cities
$result = array_slice($result, 0, 6);
$this->response->setContentType('application/json')
->setJsonContent(
array( 'totaltickets' => $total, "allcities" => $result )
);
$this->response->send();
return;
}
catch(\PDOException $e)
{
$this->response->setStatusCode('422','Invalid Payload');
$this->response->setContentType('application/json')
->setJsonContent(array(
'flash' => array(
'class' => 'danger',
'message' => $e->getMessage()
)
));
$this->response->send();
return;
}
}

Use count instead of count(result of find). Also are you sure in // get ticket cancellations you don't need group ? Then you can select all tickets for customers in 1,3 tickettype and then filter resultset.
Also can't your first $rawresulset can't be:
$rawresultset = Tickets::find (
array(
'columns' => 'customer,fromcity,tocity,tickettype ',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1,3)".$fromcitycondition
'group' => 'customer,fromcity,tocity'
));
?
$ticketCanccelations = $rawresultset->filter(function($row){
if($row->tickettype == 3) {
return $row;
}
});
$resultNumber = Tickets::count("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );

Related

How can i check all selected value quantity?

Can anyone help me? how can i check all the product selected on the select or in the option? i'm using codeigniter 3 and i want to check if there was an available stock or none but i'm new and don't know how to do it i wish someone can help me. first it was working if i select a product with 0 quantity it will not process but if i select a first product with a quantity on hand greater than 0 and selected the second one with empty qty it will still process because it only check the stocks of the first product. how can i check all the qty selected in my select option?
my model:
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check == TRUE)
{
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}
else
{
return false;
}
}
}
public function check_stock($productId, $inputQuantity)
{
$product = $this->db->get_where('products', ['id' => $productId])->row();
if(isset($product))
{
if($product->qty < $inputQuantity)
{
$this->session->set_flashdata('error','No more stock on some selected items');
return false;
}
else
{
return true;
}
}
}
and my select in view is something like this:
<select class="form-control select_group update-select" data-row-id="row_1" id="product_1" name="product[]" style="width:100%;" onchange="getProductData(1)" required>
<option disabled selected hidden value=''>--Select Products--</option>
<?php foreach ($products as $k => $v): ?>
<option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
Easiest solution is to return false as soon as you find a product that is out of stock, something like the following:
Loop through the selected products and for each one check the stock. If you encounter a product that is out of stock, return false.
If all products are in stock, create the order, then loop through the selected products again and add those to the order in the database.
I haven't tested the code below, so there may be errors. I only changed the if($check == TRUE) part and some curly braces.
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check != TRUE)
{
return false;
}
}
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}

how to count number of present(status 1 means present) for each student and input beside each student profile under present column

daily_attendances database
below is under crud_model
public function take_attendance()
{
$students = $this->input->post('student_id');
$data['timestamp'] = strtotime($this->input->post('date'));
$data['class_id'] = html_escape($this->input->post('class_id'));
$data['section_id'] = html_escape($this->input->post('section_id'));
$data['school_id'] = $this->school_id;
$data['session_id'] = $this->active_session;
$check_data = $this->db->get_where('daily_attendances', array('timestamp' => $data['timestamp'], 'class_id' => $data['class_id'], 'section_id' => $data['section_id'], 'session_id' => $data['session_id'], 'school_id' => $data['school_id']));
if($check_data->num_rows() > 0){
foreach($students as $key => $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$attendance_id = $this->input->post('attendance_id');
$this->db->where('id', $attendance_id[$key]);
$this->db->update('daily_attendances', $data);
endforeach;
}else{
foreach($students as $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$this->db->insert('daily_attendances', $data);
endforeach;
}
$this->settings_model->last_updated_attendance_data();
$response = array(
'status' => true,
'notification' => get_phrase('attendance_updated_successfully')
);
return json_encode($response);
}
public function get_presentcount_by_student_id($student_id="",$status ="") {
$checker = array(
'student_id' => $student_id,
'status' => 1
);
$presentcount_by_student_id = $this->db->get_where('daily_attendances', $checker);
return $presentcount_by_student_id->num_rows();
}
under the list.php where it shows the student name and the number of days present for each student.The code is below but it does not count number of presents for each student.It still remains 0
<td>
<?php echo $this->crud_model->get_presentcount_by_student_id($student['user_id'],'status');?>
<br>
</td>
Student detail list shown in table format
student_detail_list
use this
$count=DB::select("SELECT COUNT(*) as num FROM 'your-table-name' where status = 1 ")->get();
and you can access this by $count[0]->num

Parsing returns an empty value

I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.

PayPal does not show order summary-Omnipay

I have a function for Paypal redirection for that I pass some values in params..
It only pass the Description field doesn't shows the amount to be paid,and rest of my order summaries..
Here is my function
public function postPayment()
{
$hot_id = \Session::get('hot_id');
$user_id = \Session::get('uid');
$check_in = \Session::get('check_in');
$check_out = \Session::get('check_out');
$mem_count = \Session::get('mem_count');
$rm_no = \Session::get('rm_no');
$check_in = strtotime($check_in);
$check_in = date('Y-m-d',$check_in);
$check_out = strtotime($check_out);
$check_out = date('Y-m-d',$check_out);
$datediff = strtotime($check_out) - strtotime($check_in);
$diff = floor($datediff/(86400));
$room_prize = \DB::select("SELECT `room_prize` FROM `abserve_hotel_rooms` WHERE `room_id` = ".$_POST['room_id']);
$arr = array();
foreach ($room_prize as $key => $value) {
$arr[]= (get_object_vars($value));
}
$room_prize = array();
foreach ($arr as $key => $value) {
$room_prize[]=($value['room_prize']);
}
if($rm_no == 1)
{
$room_prize = (int) $room_prize[0] * (int) $diff;
}
else
{
$room_prize = (int) $room_prize[0] * (int) $diff * (int) $rm_no;
}
$room_prize = number_format((float)$room_prize, 2, '.', '');
$room_id = $_POST['room_id'];
$today = new DateTime();
$created_at = $today->format('Y-m-d');
$values = array('user_id' => $user_id,'hotel_id' => $hot_id,'room_id'=>$room_id,'room_prize'=>$room_prize,'check_in'=>$check_in,'check_out'=>$check_out,'created_at'=>$created_at);
\DB::table('abserve_orders')->insert($values);
$order_id = DB::select("SELECT `id` FROM `abserve_orders` WHERE `room_id` = ".$_POST['room_id']." AND `user_id` = ".$user_id);
$arr = array();
foreach ($order_id as $key => $value) {
$arr[]= (get_object_vars($value));
}
$order_id = array();
foreach ($arr as $key => $value) {
$order_id[]=($value['id']);
}
$order_id = $order_id[0];
$params = array(
'cancelUrl' => url().'/cancel_order',
'returnUrl' => url().'/payment_success',
'name' => 'new order',
'description' => 'description1',
'amount' => $room_prize,
'currency' => 'USD',
'hot_id' => $hot_id,
'room_id' => $room_id,
'user_id' => $user_id,
'check_in' => $check_in,
'check_out' => $check_out,
'order_id' => $order_id,
'nights' => $diff,
);
// print_r($params);exit;
\Session::put('params', $params);
\Session::save();
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('googley555_api1.yahoo.com');
$gateway->setPassword('3EQ6S6PB68A52JKZ');
$gateway->setSignature('AFcWxV21C7fd0v3bYYYRCpSSRl31AHaEiWOLAf5jQQ3-A9hLlhypSz9h');
$gateway->setTestMode(true);
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
}
I don't know what are missing in it..
Someone please help me..
You can't pass in arbitrary parameters such as hot_id, room_id, etc to PayPal (or omnipay) because it won't know what to do with them. PayPal is only intended to take certain parameters and the ones that PayPal does not take are ignored by Omnipay.
You may have to provide all of these extra parameters as part of the description parameter, which PayPal does understand.
Ideally these should be displayed by your application in some kind of useful format to the user before redirecting the user to the PayPal checkout page.

How can I fix this query to return only items with a certain value in its subarray?

I'm trying to modify a voting script(Thumbsup) I need this query to only return only array items that have their 'cat' => '1' in the subarray (proper term?)
<?php $items = ThumbsUp::items()->get() ?>
Here's an example of the live generated array from my database
array (
0 =>
array (
'id' => 1,
'name' => 'a',
'cat' => '1',
),
1 =>
array (
'id' => 2,
'name' => 'b',
'cat' => '2',
),
2 =>
array (
'id' => 3,
'name' => 'c',
'cat' => '2',
),
)
Is this possible by just modifying the query?
edit: heres function get()
public function get()
{
// Start building the query
$sql = 'SELECT id, name, url, cat, closed, date, votes_up, votes_down, ';
$sql .= 'votes_up - votes_down AS votes_balance, ';
$sql .= 'votes_up + votes_down AS votes_total, ';
$sql .= 'votes_up / (votes_up + votes_down) * 100 AS votes_pct_up, ';
$sql .= 'votes_down / (votes_up + votes_down) * 100 AS votes_pct_down ';
$sql .= 'FROM '.ThumbsUp::config('database_table_prefix').'items ';
// Select only either open or closed items
if ($this->closed !== NULL)
{
$where[] = 'closed = '.(int) $this->closed;
}
// Select only either open or closed items
if ($this->name !== NULL)
{
// Note: substr() is used to chop off the wrapping quotes
$where[] = 'name LIKE "%'.substr(ThumbsUp::db()->quote($this->name), 1, -1).'%"';
}
// Append all query conditions if any
if ( ! empty($where))
{
$sql .= ' WHERE '.implode(' AND ', $where);
}
// We need to order the results
if ($this->orderby)
{
$sql .= ' ORDER BY '.$this->orderby;
}
else
{
// Default order
$sql .= ' ORDER BY name ';
}
// A limit has been set
if ($this->limit)
{
$sql .= ' LIMIT '.(int) $this->limit;
}
// Wrap this in an try/catch block just in case something goes wrong
try
{
// Execute the query
$sth = ThumbsUp::db()->prepare($sql);
$sth->execute(array($this->name));
}
catch (PDOException $e)
{
// Rethrow the exception in debug mode
if (ThumbsUp::config('debug'))
throw $e;
// Otherwise, fail silently and just return an empty item array
return array();
}
// Initialize the items array that will be returned
$items = array();
// Fetch all results
while ($row = $sth->fetch(PDO::FETCH_OBJ))
{
// Return an item_id => item_name array
$items[] = array(
'id' => (int) $row->id,
'name' => $row->name,
'url' => $row->url,
'cat' => $row->cat,
'closed' => (bool) $row->closed,
'date' => (int) $row->date,
'votes_up' => (int) $row->votes_up,
'votes_down' => (int) $row->votes_down,
'votes_pct_up' => (float) $row->votes_pct_up,
'votes_pct_down' => (float) $row->votes_pct_down,
'votes_balance' => (int) $row->votes_balance,
'votes_total' => (int) $row->votes_total,
);
}
return $items;
}
thanks.
You can easily modify "get()" to add the desired functionality:
public function get($cat = null)
{
$where = array();
if ($cat !== null) {
$where[] = 'cat = '. (int) $cat;
}
// ... original code ...
}
Usage:
$items = ThumbsUp::items()->get(1);

Categories