Query Result from Database requested from Mobile App - php

I'm connecting hybrid app to the API of the web app to query certain data after search request by the user. I'm using Onsen UI to build the app.
The API code at the server side should return the merchant that the user searched for by it's name. The result should be only 1 merchant (restaurant name)
public function actionSearchMerchant()
{
if (!isset($this->data['merchant'])){
$this->msg=$this->t("Restaurant Name is required");
$this->output();
}
if (isset($_GET['debug'])){
dump($this->data);
}
if ( !empty($this->data['merchant'])){
$DbExt=new DbExt;
$DbExt->qry("SET SQL_BIG_SELECTS=1");
$total_records=0;
$data='';
$and="AND status='active' AND is_ready='2' ";
$services_filter='';
if (isset($this->data['services'])){
$services=!empty($this->data['services'])?explode(",",$this->data['services']):false;
if ($services!=false){
foreach ($services as $services_val) {
if(!empty($services_val)){
$services_filter.="'$services_val',";
}
}
$services_filter=substr($services_filter,0,-1);
if(!empty($services_filter)){
$and.=" AND service IN ($services_filter)";
}
}
}
$filter_cuisine='';
if (isset($this->data['cuisine_type'])){
$cuisine_type=!empty($this->data['cuisine_type'])?explode(",",$this->data['cuisine_type']):false;
if ($cuisine_type!=false){
$x=1;
foreach (array_filter($cuisine_type) as $cuisine_type_val) {
if ( $x==1){
$filter_cuisine.=" LIKE '%\"$cuisine_type_val\"%'";
} else $filter_cuisine.=" OR cuisine LIKE '%\"$cuisine_type_val\"%'";
$x++;
}
if (!empty($filter_cuisine)){
$and.=" AND (cuisine $filter_cuisine)";
}
}
}
$rname=$this->data['merchant'];
$stmt="SELECT * FROM
{{view_merchant}}
WHERE
restaurant_name LIKE '%\"$rname\"%'
SELECT a.*,count(*) as total_records FROM
{{view_merchant}} a
WHERE
restaurant_name LIKE '%\"$rname\"%'
$and
LIMIT 0,100
";
if (isset($_GET['debug'])){
dump($stmt);
}
if ( $res=$DbExt->rst($stmt)){
$stmtc="SELECT FOUND_ROWS() as total_records";
if ($resp=$DbExt->rst($stmtc)){
$total_records=$resp[0]['total_records'];
}
$this->code=1;
$this->msg=$this->t("Successful");
foreach ($res as $val) {
$minimum_order=getOption($val['merchant_id'],'merchant_minimum_order');
if(!empty($minimum_order)){
$minimum_order=displayPrice(getCurrencyCode(),prettyFormat($minimum_order));
}
$delivery_fee=getOption($val['merchant_id'],'merchant_delivery_charges');
if (!empty($delivery_fee)){
$delivery_fee=displayPrice(getCurrencyCode(),prettyFormat($delivery_fee));
}
/*check if mechant is open*/
$open=AddonMobileApp::isMerchantOpen($val['merchant_id']);
/*check if merchant is commission*/
$cod=AddonMobileApp::isCashAvailable($val['merchant_id']);
$online_payment='';
$tag='';
$tag_raw='';
if ($open==true){
$tag=$this->t("open");
$tag_raw='open';
if ( getOption( $val['merchant_id'] ,'merchant_close_store')=="yes"){
$tag=$this->t("close");
$tag_raw='close';
}
if (getOption( $val['merchant_id'] ,'merchant_preorder')==1){
$tag=$this->t("pre-order");
$tag_raw='pre-order';
}
} else {
$tag=$this->t("close");
$tag_raw='close';
if (getOption( $val['merchant_id'] ,'merchant_preorder')==1){
$tag=$this->t("pre-order");
$tag_raw='pre-order';
}
}
$data[]=array(
'merchant_id'=>$val['merchant_id'],
'restaurant_name'=>$val['restaurant_name'],
'address'=>$val['street']." ".$val['city']." ".$val['state']." ".$val['post_code'],
'ratings'=>Yii::app()->functions->getRatings($val['merchant_id']),
'cuisine'=>AddonMobileApp::prettyCuisineList($val['cuisine']),
'delivery_fee'=>$delivery_fee,
'minimum_order'=>$minimum_order,
'delivery_est'=>getOption($val['merchant_id'],'merchant_delivery_estimation'),
'is_open'=>$tag,
'tag_raw'=>$tag_raw,
'payment_options'=>array(
'cod'=>$cod,
'online'=>$online_payment
),
'logo'=>AddonMobileApp::getMerchantLogo($val['merchant_id']),
'offers'=>AddonMobileApp::getMerchantOffers($val['merchant_id'])
);
}
$this->details=array(
'total'=>$total_records,
'data'=>$data
);
} else $this->msg=$this->t("No restaurant found");
} else $this->msg=$this->t("Error has occurred failed restaurant info");
} else $this->msg=$this->t("Restaurant Name is required");
$this->output();
}
Basically I'm sending a parameter names "merchant" from the app that the API should get and search a table into the database called "view_merchant" column "restaurant_name" and compare the name requested by the one in the database then return it back to the app as found.
EDIT I added the JS function
var search_restaurant;
var search_cuisine;
var search_food;
$("#r").val( getStorage("search_restaurant") );
$("#c").val( getStorage("search_cuisine") );
$("#f").val( getStorage("search_food") );
function searchMerchantName()
{
var r = $('#r').val();
/*clear all storage*/
setStorage("search_restaurant",r);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(r!=""){
var options = {
merchant:r,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchMerchants.html',options);
} else{
onsenAlert( getTrans('Restaurant Name is required','merchant_is_required') );
}
}
function searchCuisine()
{
var c = $('#c').val();
/*clear all storage*/
setStorage("search_cuisine",c);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(c!=""){
var options = {
cuisine:c,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchCuisine.html',options);
} else{
onsenAlert( getTrans('Cuisine Type is required','cuisine_is_required') );
}
}
function searchFood()
{
var f = $('#f').val();
/*clear all storage*/
setStorage("search_food",f);
removeStorage('merchant_id');
removeStorage('shipping_address');
removeStorage('merchant_id');
removeStorage('transaction_type');
removeStorage('merchant_logo');
removeStorage('order_total');
removeStorage('merchant_name');
removeStorage('total_w_tax');
removeStorage('currency_code');
removeStorage('paymet_desc');
removeStorage('order_id');
removeStorage('order_total_raw');
removeStorage('cart_currency_symbol');
removeStorage('paypal_card_fee');
if(f!=""){
var options = {
foodname:f,
closeMenu:true,
animation: 'slide'
};
menu.setMainPage('searchFood.html',options);
} else{
onsenAlert( getTrans('Food Name is required','foodname_is_required') );
}
}
case "searchmerchant-page":
$("#search-text").html( getStorage("search_restaurant") );
callAjax("searchmerchant","merchant="+ getStorage("search_restaurant") );
break;
case "searchcuisine-page":
$("#search-text").html( getStorage("search_cuisine") );
callAjax("searchcuisine","cuisine="+ getStorage("search_cuisine") );
break;
case "searchfood-page":
$("#search-text").html( getStorage("search_food") );
callAjax("searchfood","foodname="+ getStorage("search_food") );
break;
case "page-home":
geoComplete();
search_address=getStorage("search_address");
if (typeof search_address === "undefined" || search_address==null || search_address=="" ) {
} else {
setTimeout('$("#s").val(search_address)', 1000);
}
translatePage();
$("#s").attr("placeholder", getTrans('Street Address,City,State','home_search_placeholder') );
//Added for Restaurant Name Search
search_restaurant=getStorage("search_restaurant");
if (typeof search_restaurant === "undefined" || search_restaurant==null || search_restaurant=="" ) {
} else {
setTimeout('$("#r").val(search_restaurant)', 1000);
}
translatePage();
$("#r").attr("placeholder", getTrans('Restaurant Name','restaurant_search_placeholder') );
//Added for Cuisine Type
search_cuisine=getStorage("search_cuisine");
if (typeof search_cuisine === "undefined" || search_cuisine==null || search_cuisine=="" ) {
} else {
setTimeout('$("#c").val(search_cuisine)', 1000);
}
translatePage();
$("#c").attr("placeholder", getTrans('Cuisine Type','cuisine_search_placeholder') );
//Added for Food Type
search_food=getStorage("search_food");
if (typeof search_food === "undefined" || search_food==null || search_food=="" ) {
} else {
setTimeout('$("#f").val(search_food)', 1000);
}
translatePage();
$("#f").attr("placeholder", getTrans('Food Name','food_search_placeholder') );
break;
function searchResultCallBack(address)
{
search_address=address;
}
function searchMerchantsCallBack(merchant)
{
search_restaurant=merchant;
}
function searchCuisineCallBack(cuisine)
{
search_cuisine=cuisine;
}
function searchFoodCallBack(foodname)
{
search_food=foodname;
}

Your SQL statement will be:
SELECT * FROM view_merchant WHERE lower(restaurant_name)=?
You will want to toLowerCase() your passed value $this->data['merchant'] so you are finding the restaurant regardless of casing. The only issue is that this will return multiple records if there are ones with the same name.

Related

How to append ORDERBY with where condition in php

I am working with mysql and Rest Api in php,I want to use "orderby" according to condition (if "filterId"==3 or 4). In other words:
If I pass filterId='3' then query should be like SELECT ......ORDER by p.sp ASC/DESC
If I pass filterId='4' then query should be like SELECT ......ORDER by m.merchantName ASC/DESC
If I pass both parameters,filterId='3' and filterId='4' then query should be like SELECT ......ORDER by m.merchantName,p.sp ASC/DESC
If not pass filterId='3' or filterId='4' then orderby not apply/append
How can I do this? Here is my current code:
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
// echo "<pre>";print_R($data);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="1")
{
}
if($d->filter_id=="3")
{
}
}
}
Try this.
$query = "Select * from .... ORDER BY";
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
// echo "<pre>";print_R($data);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="1")
{
$query .='ORDER BY p.asp';
}
else if($d->filter_id=="3")
{
$query .='ORDER BY m.merchantName';
}
else
{
break;
}
}
}
For your third condition, you might have to use in_array_all() as below:
function in_array_all($lookfor, $mainarray) {
return empty(array_diff($lookfor, $mainarray));
}
//Try this
$query = 'select * from ...';
$order_by_clause = '';
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="3")
{
$order_by_clause = 'ORDER BY p.sp ASC';
}
else if($d->filter_id=="4")
{
$order_by_clause = 'ORDER BY m.merchantName';
}
else if(($d->filter_id=="3") && if($d->filter_id=="4"))
{
$order_by_clause = 'ORDER BY m.merchantName,p.sp';
}
else if(!(($d->filter_id!="3") || if($d->filter_id!="4"))
{
$order_by_clause = '';
}
}
}
}
$query .= $order_by_clause;

Call to undefined method MyDbCon

okay I'm getting the error Call to undefined method MyDbCon and I'm a newbie so please assist me, what am I doing wrong here? be gentle lol
use Zend\Db\Sql\Select;
function getStudentsByMst(&$response,$mst_id,$stud_id=true,$now=true)
{ if(!ctype_digit($mst_id))
{ $response = array(
'code' => HTTP_Status::BAD_REQUEST,
'message' => 'Registration ID cannot be digits only'
);
return false;
}
}
include_once('credentials.db.php');
if(empty($_POST['stud_id']) == FALSE)
{
$barcode = htmlentities($_POST['stud_id']);
//checking if the barcode exist in the database
$dbh=new MyDbCon;
$barcode_check = $dbh->query("select * from usats where stud_id='$stud_enrolmentno'");
//extracting the status of the item
if($barcode_check->rowCount() > 0)
{
while($row = $barcode_check->fetch(PDO::FETCH_OBJ))
{
$presence = $row->presence;
}
}
if($barcode_check->rowCount() > 0 && $presence == '1')
{
//updating the database table barcode for student presence/absence
$addAttd = $dbh->exec("UPDATE usats SET status='0' where stud_id= '$stud_enrolmentno'");
if($addAttd > 0)
{
echo "<script> alert('Successful');</script>";
}
}
}
?>

vTiger Custom Field Validation beforesave

I have created a custom module on vTiger 6.5.
I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.
Please see my code below. Thanks!
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {}
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave.final') {}
if($eventName == 'vtiger.entity.aftersave') {
}
}
}
}
?>
After doing some searching around and looking at other peoples event handlers I managed to solve this by changing:
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
to
if($eventName == 'vtiger.entity.beforesave') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
Now I want to see if I can display the message and then give a link to go back to the entity module with all the fields still full.
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database
Here is an example:
In your Edit.js:
donCache : {},
checkDon : function(details) {
// alert("checkOverlap");
var aDeferred = jQuery.Deferred();
var params = {
'module' : 'Affectations',
'action' : "checkAffectAmount",
'mode': 'CtrlAffectAmount',
'recordId' : details.don,
'montant' : details.montant
}
AppConnector.request(params).then(
function(data) {
if (data.success == true) {
// console.log(data.result);
var statut = data.result.statut;
var reste = data.result.reste;
if(statut == "error"){
aDeferred.reject(data);
}else {
aDeferred.resolve(data);
}
}
},
function(error,err){
aDeferred.reject();
}
);
return aDeferred.promise();
},
registerRecordPreSaveEvent : function(form) {
var thisInstance = this;
if (typeof form == 'undefined') {
form = this.getForm();
}
form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
var check = false;
var recordId = jQuery('input[name="record"]').val();
if (!recordId || recordId) {
var montant_affectation = jQuery("input[name='affectations_montant']").val();
var don_id = jQuery("input[name='affectations_potentialid']").val();
var params = {};
if (!(check in thisInstance.donCache)) {
thisInstance.checkDon({
'montant' : montant_affectation,
'don': don_id
}).then(
function(data){
thisInstance.donCache[check] = data['success'];
form.submit();
},
function(data, err){
thisInstance.donCache[check] = data['success'];
var reste = data.result.reste;
var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure de ")+ reste +app.vtranslate(" Euros au montant du don");
Vtiger_Helper_Js.showPnotify(msg);
delete thisInstance.donCache[check];
}
);
} else {
delete thisInstance.donCache[check];
return true;
}
e.preventDefault();
}
})
},
The PHP part in modules/isa/actions:
<?php
/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/
class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {
function __construct() {
$this->exposeMethod('CtrlAffectAmount');
}
public function checkPermission(Vtiger_Request $request) {
$moduleName = $request->getModule();
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
$permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());
if(!$permission) {
throw new AppException('LBL_PERMISSION_DENIED');
}
}
public function process(Vtiger_Request $request) {
$mode = $request->getMode();
if(!empty($mode) && $this->isMethodExposed($mode)) {
$this->invokeExposedMethod($mode, $request);
return;
}
}
function CtrlAffectAmount(Vtiger_Request $request){
global $adb,$log;
$log->debug("ALTAIR CtrlAffectAmount OK");
$recordId = $request->get('recordId');
$montant = $request->get('montant');
// $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
$query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
$sommeAffectation = $adb->query_result($query,0,"sommeaffectation");
$query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
$montantDon = $adb->query_result($query,0,"amount");
if ( ($sommeAffectation + $montant) == $montantDon) {
$statut = "ok";
$reste = "";
} else if( ($sommeAffectation + $montant) > $montantDon) {
$statut = "error";
$reste = ($sommeAffectation + $montant) - $montantDon;
}
$value = array('statut'=>$statut, 'reste'=>$reste);
$response = new Vtiger_Response();
$response->setEmitType(Vtiger_Response::$EMIT_JSON);
$response->setResult($value);
$response->emit();
}
}
Oh. you have 1 invalid error here. please change:
if($eventName == 'vtiger.entity.beforesave') {
$currentAmount = $entityData->get('currentamount');
if($currentAmount > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}

MongoDB MapReduce returning null values in PHP (but works in Javascript)

I am trying to make a Map-Reduce command in PHP with exactly the same functions as in pure JavaScript and surprisingly the result is not the same. I have null values in PHP :-(
I have an "employees" collection, for each employee there is a list of "departments" to which he/she belongs.
So the Javascript map-reduce code (which works) to get the number of employees by department will be:
map = function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};
reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};
retorno = db.runCommand({
"mapreduce": "employees",
"map": map,
"reduce": reduce,
"out": "employees_by_department"
});
if (retorno.ok != 1) {
print(retorno.errmsg);
};
resultado = db.employees_by_department.find();
while ( resultado.hasNext() ) {
printjson( resultado.next() );
}
And the equivalent PHP code (with null values) will be:
<?php
try {
$connection = new MongoClient( "mongodb://localhost" );
$db = $connection->selectDB("employees");
} catch (Exception $e) {
printf("Error: %s: %s\n", "Error al conectarse a MongoDB: ", $e->getMessage());
die();
}
$map = new MongoCode("function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};");
$reduce = new MongoCode("reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};");
$retorno = $db->command(array(
"mapreduce" => "employees",
"map" => $map,
"reduce" => $reduce,
"out" => "employees_by_department_php"
));
if ($retorno["ok"] =! 1) {
print($retorno["errmsg"]);
}
else {
$resultado = $db->selectCollection("employees_by_department_php")->find();
foreach($resultado as $dep) {
printf("_id: \"%s\", value: %d\n", $dep["_id"], $dep["value"]);
}
}
?>
Any ideas?
UUpppss!! Solved! The problem was a typo error (a copy-paste problem) :-|
In PHP the first line of the reduce function, where it was
$reduce = new MongoCode("reduce = function(key, values) {
should be
$reduce = new MongoCode("function(key, values) {

Symfony2 , improve query performance

Does anybody know how to improve performance of this query?
I'm using doctrine DQL model, here's the code
(it takes 5-6 sec without pagination bundle)
Controller:
$data = $this->getDoctrine()
->getEntityManager('sparcs')
->getRepository('TruckingMainBundle:BCT_CNTR_EVENTS')
->findOperationReport(Convert::serializeToArray($request->getContent()));
Repository method:
public function findOperationReport($condition = array()) {
$data = $condition['record'];
$move_types = array();
$result = $this->createQueryBuilder("sp")
->addSelect("sp");
// move types
if(isset($data['vessel_discharge'])) {
//$move_types[] = $this->container->getParameter('MOVE_TYPE.VESSEL_DIS');
$move_types[] = 'VY';
}
if(isset($data['vessel_loading'])) {
//$move_types[] = $this->container->getParameter('MOVE_TYPE.VESSEL_LOAD');
$move_types[] = 'YV';
}
if(isset($data['truck_out'])) {
$move_types[] = 'TC';
}
if(isset($data['truck_in'])) {
$move_types[] = 'CT';
}
if(isset($data['stuffing'])) {
//$move_types[] = 'CT';
}
if(isset($data['unstuffing'])) {
//$move_types[] = 'CT';
}
if(isset($data['rail_in'])) {
$move_types[] = 'YR';
}
if(isset($data['rail_out'])) {
$move_types[] = 'RY';
}
if(count($move_types) > 0) {
$result->andWhere('sp.move_type IN (:move_type)')
->setParameter('move_type',$move_types);
} else {
$result->andWhere("1 = 2");
}
//container types
if(isset($data['empty']) && isset($data['full'])) {
//skipping
}
elseif (isset($data['empty'])) {
$result->andWhere('sp.ctnr_status = :ctnr_status')
->setParameter('ctnr_status',self::CTNR_EMPTY);
}
elseif (isset($data['full'])) {
$result->andWhere('sp.ctnr_status = :ctnr_status')
->setParameter('ctnr_status',self::CTNR_FULL);
if(isset($data['weight_from'])) {
$result->andWhere("cast(replace([weight],',','.') as float) :weight_from")
->setParameter('weight_from',$data['weight_from']);
echo 'weight from';
}
if(isset($data['weight_to'])) {
$result->andWhere('sp.weight <= :weight_to')
->setParameter('weight_to',(string)$data['weight_to']);
}
}
/*
//excpetion
$result->andWhere('sp.move_type NOT IN (:move_type_not)')
->setParameter('move_type_not',array('TY','YT'));
*/
if(isset($data['today']) || isset($data['yesterday'])) {
//yesterday
if(isset($data['yesterday'])) {
$yesterday = new \DateTime(date("Ymd"));
$interval = new \DateInterval("P1D");
$interval->invert = 1;
$yesterday->add($interval);
}
//yesterday + today
if(isset($data['today']) && isset($data['yesterday'])) {
$result->andWhere('sp.move_time >= :yesterday')
->setParameter('yesterday',$yesterday->format("Ymd000000"));
}
elseif(isset($data['yesterday'])) {
$result->andWhere('sp.move_time >= :yesterday_from AND sp.move_time <= :yesterday_to')
->setParameter('yesterday_from',$yesterday->format("Ymd000000"))
->setParameter('yesterday_to',$yesterday->format("Ymd235959"));
}
elseif(isset($data['today'])) {
$result->andWhere("sp.move_time = :today")
->setParameter('today',date("Ymd000000"));
}
}
else {
//date conditions
$date_from = new \DateTime(strtotime($data['date_from']));
$date_to = new \DateTime(strtotime($data['date_to']));
$result->andWhere("sp.move_time >= :date_from")
->setParameter('date_from',$date_from->format("Ymd000000"));
$result->andWhere("sp.move_time <= :date_to")
->setParameter('date_to',$date_to->format("Ymd235959"));
}
//booking
if(isset($data['booking']) && !empty($data['booking'])) {
$result->andWhere("sp.booking = :booking")
->setParameter('booking',$data['booking']);
}
//is reffer
if(isset($data['reefer'])) {
$result->andWhere("sp.reefer_flag = :reefer")
->setParameter('reefer','Y');
}
//is damage
if(isset($data['damage'])) {
$result->andWhere("sp.hazards <> ''"); //$result->expr()->neq("sp.hazards","")
}
//specific_type
if(isset($data['specific_type'])) {
/*
$result->andWhere("sp.equip_type <> :specific_type")
->setParameter('specific_type',$data['specific_type']);
*
*/
}
//specific_type
if(isset($data['container_type_20']) && isset($data['container_type_40'])) {
//$result->andWhere("sp.equip_type <> :specific_type")
// ->setParameter('specific_type',$data['specific_type']);
}
elseif(isset($data['container_type_20'])) {
$result->andWhere($result->expr()->substring('sp.equip_type',1,1)." = :equip_type")
->setParameter('equip_type',2);
}
elseif(isset($data['container_type_40'])) {
$result->andWhere($result->expr()->substring('sp.equip_type',1,1)." = :equip_type")
->setParameter('equip_type',4);
}
return $result->setMaxResults(30)->getQuery();
}
If I use KnpPaginationBundle ,then it takes more than 27 sec )
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$data,
2/*page number*/,
10/*limit per page*/
);
I can execute a native sql query without KnpPaginatorBundle (and it takes 0.333 ms)
//START
$query = $this->getDoctrine()
->getEntityManager('sparcs')->getConnection()->executeQuery (
'SELECT *
FROM (SELECT Row_number()
OVER (
ORDER BY (SELECT 0)) AS "doctrine_rownum",
b0_.id AS id0,
b0_.container AS container1,
b0_.container_use_key AS container_use_key2,
b0_.line AS line3,
b0_.billable_line AS billable_line4,
b0_.move_time AS move_time5,
b0_.move_type AS move_type6,
b0_.pos_from AS pos_from7,
b0_.pos_to AS pos_to8,
b0_.rotation_nbr AS rotation_nbr9,
b0_.from_che AS from_che10,
b0_.to_che AS to_che11,
b0_.from_che_kind AS from_che_kind12,
b0_.to_che_kind AS to_che_kind13,
b0_.from_che_op AS from_che_op14,
b0_.to_che_op AS to_che_op15,
b0_.pow AS pow16,
b0_.internal_truck AS internal_truck17,
b0_.lifter AS lifter18,
b0_.quay_crane AS quay_crane19,
b0_.license_plate AS license_plate20,
b0_.trucker_id AS trucker_id21,
b0_.trucker_name AS trucker_name22,
b0_.arrv_qual AS arrv_qual23,
b0_.arrv_carrier AS arrv_carrier24,
b0_.dept_qual AS dept_qual25,
b0_.dept_carrier AS dept_carrier26,
b0_.invoyage AS invoyage27,
b0_.outvoyage AS outvoyage28,
b0_.lloyds_code AS lloyds_code29,
b0_.load_port AS load_port30,
b0_.disch_port AS disch_port31,
b0_.destination AS destination32,
b0_.equip_type AS equip_type33,
b0_.bundle AS bundle34,
b0_.ctnr_category AS ctnr_category35,
b0_.ctnr_status AS ctnr_status36,
b0_.ctnr_stopped AS ctnr_stopped37,
b0_.commodity AS commodity38,
b0_.weight AS weight39,
b0_.damage AS damage40,
b0_.reefer_temp AS reefer_temp41,
b0_.reefer_flag AS reefer_flag42,
b0_.damage_details AS damage_details43,
b0_.seal_1 AS seal_144,
b0_.railcar_id AS railcar_id45,
b0_.dwell_time AS dwell_time46,
b0_.special_stow AS special_stow47,
b0_.service AS service48,
b0_.booking AS booking49,
b0_.release_note AS release_note50,
b0_.cmr_number AS cmr_number51,
b0_.forwarding_agent AS forwarding_agent52,
b0_.cargo_agent AS cargo_agent53,
b0_.invoice_number AS invoice_number54,
b0_.invoice_status AS invoice_status55,
b0_.last_flag AS last_flag56,
b0_.sparcs_user AS sparcs_user57,
b0_.program AS program58,
b0_.id AS id59,
b0_.container AS container60,
b0_.container_use_key AS container_use_key61,
b0_.line AS line62,
b0_.billable_line AS billable_line63,
b0_.move_time AS move_time64,
b0_.move_type AS move_type65,
b0_.pos_from AS pos_from66,
b0_.pos_to AS pos_to67,
b0_.rotation_nbr AS rotation_nbr68,
b0_.from_che AS from_che69,
b0_.to_che AS to_che70,
b0_.from_che_kind AS from_che_kind71,
b0_.to_che_kind AS to_che_kind72,
b0_.from_che_op AS from_che_op73,
b0_.to_che_op AS to_che_op74,
b0_.pow AS pow75,
b0_.internal_truck AS internal_truck76,
b0_.lifter AS lifter77,
b0_.quay_crane AS quay_crane78,
b0_.license_plate AS license_plate79,
b0_.trucker_id AS trucker_id80,
b0_.trucker_name AS trucker_name81,
b0_.arrv_qual AS arrv_qual82,
b0_.arrv_carrier AS arrv_carrier83,
b0_.dept_qual AS dept_qual84,
b0_.dept_carrier AS dept_carrier85,
b0_.invoyage AS invoyage86,
b0_.outvoyage AS outvoyage87,
b0_.lloyds_code AS lloyds_code88,
b0_.load_port AS load_port89,
b0_.disch_port AS disch_port90,
b0_.destination AS destination91,
b0_.equip_type AS equip_type92,
b0_.bundle AS bundle93,
b0_.ctnr_category AS ctnr_category94,
b0_.ctnr_status AS ctnr_status95,
b0_.ctnr_stopped AS ctnr_stopped96,
b0_.commodity AS commodity97,
b0_.weight AS weight98,
b0_.damage AS damage99,
b0_.reefer_temp AS reefer_temp100,
b0_.reefer_flag AS reefer_flag101,
b0_.damage_details AS damage_details102,
b0_.seal_1 AS seal_1103,
b0_.railcar_id AS railcar_id104,
b0_.dwell_time AS dwell_time105,
b0_.special_stow AS special_stow106,
b0_.service AS service107,
b0_.booking AS booking108,
b0_.release_note AS release_note109,
b0_.cmr_number AS cmr_number110,
b0_.forwarding_agent AS forwarding_agent111,
b0_.cargo_agent AS cargo_agent112,
b0_.invoice_number AS invoice_number113,
b0_.invoice_status AS invoice_status114,
b0_.last_flag AS last_flag115,
b0_.sparcs_user AS sparcs_user116,
b0_.program AS program117
FROM bct_cntr_events b0_
WHERE b0_.move_type IN ( \'YY\',\'YV\',\'VY\',\'TY\' )
AND b0_.move_time >= \'20120910000000\'
AND b0_.move_time <= \'20120912300000\') AS doctrine_tbl
WHERE "doctrine_rownum" BETWEEN 11 AND 20 '
)->fetchAll();
Think about add memcache as a cache driver.
Think about stopping hydrating results to entity objects (time & cpu consuming)
$query->getResult(Query::HYDRATE_ARRAY);
Avoid conditions with wildcard strings.
Try PagerFanta.

Categories