Symfony2 , improve query performance - php
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.
Related
Google cloud task divide into subtasks by firebase data
I have a google task which gets all companies from my firebase database. I then go through each of those companies in a loop and call additional task for updating each specific company. My problem is that my companies count is increasing and when doing foreach like this i can get into memory limit issues. Here is the actual code for calling the tasks and subtasks: $router->get('companies', function () use ($router) { $slackDataHelpersService = new \App\Services\SlackDataHelpersService(); $companiesDocuments = $slackDataHelpersService->getCompanies(); foreach ($companiesDocuments->documents() as $document) { $cid = $document->id(); createTask('companies', 'updateCompany', "{$cid}"); } return res(200, 'Task done'); }); How can i separate my initial companies documents into chunks and call a task for each of those chunks? For example, a task that will go through every 100 documents instead of the whole list? Here is what i tried without success(i used members in this case): $router->get('test2', function () use ($router) { $db = app('firebase.firestore')->database(); $membersRef = $db->collection('companies')->document('slack-T01L7H2NDPB')->collection('members'); $query = $membersRef->orderBy('created', 'desc')->limit(10); $perPage = 10; $batchCount = 10; $lastCreated = null; while ($batchCount == $perPage) { $loopQuery = clone $query; if ($lastCreated != null) { $loopQuery->startAfter($lastCreated); } $docs = $loopQuery->documents(); $docsRows = $docs->rows(); $batchCount = count($docsRows); if ($batchCount > 1) { $lastCreated = $docsRows[$batchCount - 1]; } echo $lastCreated['created']; //createTasksByDocs($docs); } //return res(200, 'Task done'); });
I ended up making a function which uses a while loop and loops until it reaches the limit: function paginateCollections($ref, $limit, $functionName) { $query = $ref->orderBy('created', 'desc')->limit($limit); $perPage = $limit; $batchCount = $limit; $lastCreated = null; while ($batchCount == $perPage) { $loopQuery = clone $query; if ($lastCreated != null) { $loopQuery = $loopQuery->startAfter([$lastCreated]); } $docs = $loopQuery->documents(); $docsRows = $docs->rows(); $batchCount = count($docsRows); if ($batchCount > 1) { $lastCreated = $docsRows[$batchCount - 1]['created']; } if (function_exists($functionName)) { $functionName($docs); } } }
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;
how to implode and insert values into db in codeigniter?
How to implode and insert values into the database in CodeIgniter? I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this: id userid q_id answer_id time_taken 1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7 in my controller: public function insert_result() { $this->load->model('quiz_models'); $user_id=$this->input->post('user_id'); $qq_id=$this->input->post('questionid'); $answer_id=$this->input->post('AnswerID'); $time_taken=$this->input->post('timetaken'); $question_no=$this->input->post('question_no'); $bd = "$question_no"; switch ($bd) { case"1": $data=array('user_id'=>$user_id, 'q_id'=>$qq_id, 'answer_id'=>$answer_id, 'time_taken'=>$time_taken); $this->quiz_models->insert_result($data); break; case"2": quiz_test(); break; case"3": quiz_test(); break; case"4": quiz_test(); break; case"5": quiz_test(); $this->session->unset_userdata('lastids'); break; default: echo "something is wrong"; } } public function quiz_test() { $this->load->model('quiz_models'); $quiz=$this->quiz_models->quiz_test(); foreach($quiz as $row){ $qid=$row->q_id; $ans=$row->answer_id; $time=$row->time_taken; $a = array("$qq_id","$qid"); $b = array("$answer_id","$ans"); $c = array("$time_taken","$time"); $comma = implode(",",$a); $comma1 = implode(",",$b); $comma2 = implode(",",$c); $data=array('q_id'=>$comma, 'answer_id'=>$comma1, 'time_taken'=>$comma2); $this->quiz_model->update_result($data); } } } and Model: function insert_result($data) { $this->dbb->insert('results',$data); $sectio=$this->db->insert_id(); $this->session->set_userdata('lastids',$sectio); } function quiz_test() { $ses_id = $this->session->userdata('lastids'); $sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'"; $query = $this->dbb->query($sql); $result = $query->result(); return $result; } function update_result($data){ $ses_id = $this->session->userdata('lastids'); $this->db->where('id',$ses_id); $this->db->update('results',$data); } when i run it nothing happened,not showing any error where do i mistake? pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure Normalize your Data You should prevent to store your information in the table like that. It should be possible to normalize your data properly. If you dont know how to do that the following link could be interesting: Normalization in MYSQL However a possible solution would be to structure your data: In order to do that - create a save Method in your Model to split between update and insert - this model could look like class Quiz_Models { private $arrPostData; public function save($arrPostData = false) { $this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData; $id = $this->session->userdata("lastids"); if ($id) { $query = $this->db ->select("*") ->from("results") ->where("id",$id) ->get(); if ($query->num_rows() == 1) { $this->update($query->row(0)); } else return false; } else { $this->insert(); } if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids"); } private function update($objData) { $objCollection = new Quiz_Collection(); $objCollection->userId = $objData->userid; $objCollection->id = $objData->id; $arrData = explode($objData->q_id); foreach($arrData AS $key => $quizId) { $objQuiz = new stdClass(); $objQuiz->q_id = $quizId; $objQuiz->answer_id = explode($objData->answer_id)[$key]; $objQuiz->time_taken = explode($objData->answer_id)[$key]; $objCollection->append($objQuiz); } $objQuizFromPost = new stdClass(); $objQuizFromPost->q_id = $this->arrPostData["questionid"]; $objQuizFromPost->answer_id = $this->arrPostData['AnswerID']; $objQuizFromPost->time_taken = $this->arrPostData['timetaken']; $objCollection->addQuizFromPost($objQuizFromPost); $this->db ->where("id",$objCollection->id) ->update("results",$objCollection->getDbData()); } private function insert() { $objCollection = new Quiz_Collection(); $objCollection->userId = $this->arrPostData['user_id']; $objQuizFromPost = new stdClass(); $objQuizFromPost->q_id = $this->arrPostData["questionid"]; $objQuizFromPost->answer_id = $this->arrPostData['AnswerID']; $objQuizFromPost->time_taken = $this->arrPostData['timetaken']; $objCollection->addQuizFromPost($objQuizFromPost); $this->db->insert("results",$objCollection->getDbData()); $this->session->set_userdata("lastids", $this->db->insert_id()); } } as an addition you need a Collection Object (put this below your model) class Quiz_Collection extends Array_Object { public $userId = 0; public $id = 0; public function addQuizFromPost($objQuiz) { if (intval($objQuiz->q_id) > 0) { foreach($this AS $key => $obj) { if ($obj->q_id == $objQuiz->q_id) { $this->offsetSet($key, $objQuiz); return true; } } $this->append($objQuiz); return true; } return false; } public function sortQuizData($objA, $objB) { if ($objA->q_id == $objB->q_id) return 0; return ($objA->q_id < $objB->q_id) ? -1 : 1; } public function getDbData() { $this->uasort(array($this,"sortQuizData")); $arrData = $this->getArrayCopy(); $arrDbData = [ "userid" => $this->userId, "q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","), "answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","), "time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","), ]; return $arrDbData; } } pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
Exclude Currency Country from Script
I need to tweak our script slightly. What would be the modification to get the INR currency below to NOT get divided by 1.2 and NOT have the rounding occur, like the other currencies (except GBP) as per below? <?php require_once "tools.php"; function GetRate($curCode) { if ($curCode=="GBP") return 1; if ($curCode=="USD") return 1.5399; if ($curCode=="AUD") return 1.9838; if ($curCode=="CAD") return 1.9168; if ($curCode=="INR") return 1; /* $url = "http://rate-exchange.appspot.com/currency?from=GBP&to=".$curCode; $s = ReadPageCURL($url); if ($ar = GetStringBetweenTags('rate":',',',$s)) return floatval(trim($ar[0]));*/ else return 1; } function Convert($s,$curCode) { $path = "/home2/busi6292/public_html/orders/convertcurrency/automatic/"; if ($curCode=="GBP") { $resFile=$path."bigcommerce_uk.xml"; $addURL="?setCurrencyId=1"; } else if ($curCode=="USD") { $resFile=$path."bigcommerce_usa.xml"; $addURL="?setCurrencyId=3"; } else if ($curCode=="INR") { $resFile=$path."bigcommerce_uk_revised2.xml"; $addURL="?setCurrencyId=1"; } else if ($curCode=="CAD") { $addURL="?setCurrencyId=6"; $resFile=$path."bigcommerce_canada.xml"; } else if ($curCode=="AUD") { $addURL="?setCurrencyId=4"; $resFile=$path."bigcommerce_australia.xml"; } $curRate = GetRate($curCode); echo ("<br>$curCode<br>$curRate<br>$resFile<Br><br>"); $eTag=' GBP'; $eTagLen=strlen($eTag); $res=$s; if ($curCode!="GBP") { $res=str_replace(".html]]></link>",".html".$addURL."]]></link>",$res); $res=str_replace("/]]></link>","/".$addURL."]]></link>",$res); while (($ep=strpos($res,$eTag,0))!==false) { if (#file_exists("stop.txt")) { #unlink("stop.txt"); die ("<br>stopped"); } $sp=$ep-1; while ($sp>=0) { if (substr($res,$sp,1)=="[") { $sp++; $lastPos=$ep+$eTagLen; $s1=substr($res,$sp,$lastPos-$sp); //pre-divide the s1 force to float and apply pre-rounding $preDivide = round((floatval($s1)/1.2), 2); //old line before pre-divison and rounding change //$newPrice=sprintf("%1.4f",(floatval($s1)/1.2*floatval($curRate)))." ".$curCode; $newPrice=sprintf("%1.4f",($preDivide*floatval($curRate)))." ".$curCode; //double checks the round and forces only 2 decimal places $roundPrice = number_format((float)$newPrice, 2, '.', ''); //old line before pre-division and rounding change // $res=str_replace("[".$s1."]","[".$newPrice."]",$res); $res=str_replace("[".$s1."]","[".$roundPrice."]",$res); file_put_contents($resFile,$res); $FileSize2 = filesize($resFile); //WriteToLog("log_".$curCode.".txt","1. sp=$sp, ep=$ep, lastPos=$lastPos, old price = $s1, newPrice = $newPrice. x1=".sprintf("%1.4f",floatval($s1)/1.2)." x0=".sprintf("%1.4f",$s1)); //die ("s1=$s1, newPrice=$newPrice"); break; } $sp--; } //WriteToLog("log_".$curCode.".txt","2. sp=$sp, ep=$ep, lastPos=$lastPos, old price = $s1, newPrice = $newPrice. x1=".sprintf("%1.4f",floatval($s1)/1.2)." x0=".sprintf("%1.4f",$s1)); } file_put_contents($resFile,$res); $FileSize1 = filesize($resFile); if($FileSize1 == '0' || $FileSize2 == '0') { $t=#microtime(true); $url = "http://www.MYDOMAIN.co.uk/xml.php?GSF=88d6badb/GB"; $s = ReadPageCURL($url); file_put_contents("original.xml",$s); Convert($s,"GBP"); Convert($s,"USD"); Convert($s,"CAD"); Convert($s,"AUD"); Convert($s,"INR"); $t=#microtime(true)-$t; echo "<br>Cron finished, elapsed time = ".sprintf("%1.3f",$t); } // if ($curCode!="GBP")die ("<br>abort"); } // replace prices } $t=#microtime(true); $url = "http://www.MYDOMAIN.co.uk/xml.php?GSF=88d6badb/GB"; $s = ReadPageCURL($url); file_put_contents("original.xml",$s); Convert($s,"GBP"); Convert($s,"USD"); Convert($s,"CAD"); Convert($s,"AUD"); Convert($s,"INR"); $t=#microtime(true)-$t; echo "<br>Cron finished, elapsed time = ".sprintf("%1.3f",$t); ?>
Just Check for INR before executing the line. if($curCode != "INR") { $preDivide = round((floatval($s1)/1.2), 2); } else { $preDivide = floatval($s1);//or whatever treatment you want to give to INR }
Using $this when not in object context - MyBB
So, I'm using MyBB forums, and I go to moderate a thread, and get this error. Fatal error: Using $this when not in object context in C:\zpanel\hostdata\sdcore\public_html\forums\inc\class_moderation.php on line 642 the code on line 642 is $this->delete_thread($mergetid); And the surrounding code (just in case) $db->delete_query("threadsubscriptions", "tid = '{$mergetid}'"); update_first_post($tid); $arguments = array("mergetid" => $mergetid, "tid" => $tid, "subject" => $subject); $plugins->run_hooks("class_moderation_merge_threads", $arguments); $this->delete_thread($mergetid); and the delete thread function function delete_thread($tid) { global $db, $cache, $plugins; $tid = intval($tid); $plugins->run_hooks("class_moderation_delete_thread_start", $tid); $thread = get_thread($tid); $userposts = array(); // Find the pid, uid, visibility, and forum post count status $query = $db->query(" SELECT p.pid, p.uid, p.visible, f.usepostcounts FROM ".TABLE_PREFIX."posts p LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid) WHERE p.tid='{$tid}' "); $pids = array(); $num_unapproved_posts = $num_approved_posts = 0; while($post = $db->fetch_array($query)) { $pids[] = $post['pid']; $usepostcounts = $post['usepostcounts']; if(!function_exists("remove_attachments")) { require MYBB_ROOT."inc/functions_upload.php"; } // Remove attachments remove_attachments($post['pid']); // If the post is unapproved, count it! if($post['visible'] == 0 || $thread['visible'] == 0) { $num_unapproved_posts++; } else { $num_approved_posts++; // Count the post counts for each user to be subtracted ++$userposts[$post['uid']]; } } // Remove post count from users if($usepostcounts != 0) { if(is_array($userposts)) { foreach($userposts as $uid => $subtract) { $db->update_query("users", array('postnum' => "postnum-{$subtract}"), "uid='".intval($uid)."'", 1, true); } } } // Delete posts and their attachments if($pids) { $pids = implode(',', $pids); $db->delete_query("posts", "pid IN ($pids)"); $db->delete_query("attachments", "pid IN ($pids)"); $db->delete_query("reportedposts", "pid IN ($pids)"); } // Implied counters for unapproved thread if($thread['visible'] == 0) { $num_unapproved_posts += $num_approved_posts; } // Delete threads, redirects, subscriptions, polls, and poll votes $db->delete_query("threads", "tid='$tid'"); $db->delete_query("threads", "closed='moved|$tid'"); $db->delete_query("threadsubscriptions", "tid='$tid'"); $db->delete_query("polls", "tid='$tid'"); $db->delete_query("pollvotes", "pid='".$thread['poll']."'"); $db->delete_query("threadsread", "tid='$tid'"); $db->delete_query("threadratings", "tid='$tid'"); $updated_counters = array( "posts" => "-{$num_approved_posts}", "unapprovedposts" => "-{$num_unapproved_posts}" ); if($thread['visible'] == 1) { $updated_counters['threads'] = -1; } else { $updated_counters['unapprovedthreads'] = -1; } if(substr($thread['closed'], 0, 5) != "moved") { // Update forum count update_forum_counters($thread['fid'], $updated_counters); } $plugins->run_hooks("class_moderation_delete_thread", $tid); return true; } How would I go about fixing this?