I keep seeing Waiting for Cache and it takes at least 30 minutes to get
the response.
Is there a better way?
Here's the link:
http://tapnapp.co/planning/phpScripts/getFullViewTasks.php?counter=1&sDateHour=1525154400&eDateHour=1527793200
And here is the code:
<?php
if (isset($_GET['counter'])) {
require_once '../functions.php';
$sDateHour = $_GET['sDateHour'];
$eDateHour = $_GET['eDateHour'];
$now = time() - 24*60*60;
$fn = new Func;
$fn->select('id_profile, groupe','profile',''," date_f_contract>='$now' AND groupe>0");
$sel = new Func;
$getHrName = new Func;
while ($row = mysqli_fetch_assoc($fn->select)) {
$pr_id = $row['id_profile'];
$sel->select('*','counter',''," from_interval>='$sDateHour' AND to_interval<='$eDateHour' AND id_profile='$pr_id'");
$nr= mysqli_num_rows($sel->select);
if ($nr > 0) {
//here we have to do the total counter
$totalCounter = 0;
$from_interval = 0;
$to_interval = 0;
$name = "";
$tmp_id_profile = 0;
$tmp_f_int = 0;
$tmp_to_int = 0;
while ($r = mysqli_fetch_assoc($sel->select)) {
$frint = $r['from_interval'];
$toint = $r['to_interval'];
//$counter_ct = $r['counter'];
$totalCounter += $counter_ct;
$getHrName->select('libelle AS lbl, COUNT(libelle) AS totalHr',"horraire",""," date_heure_deb>='$frint' AND date_heure_fin<='$toint' AND id_profile='$pr_id' GROUP BY libelle ORDER BY totalHr DESC LIMIT 1");
$rr = mysqli_fetch_assoc($getHrName->select);
$r['hrname'] = $rr['lbl'];
$name = $rr['lbl'];
$r['counter'] = $rr['totalHr'];
/*
$from_interval=$frint;
$to_interval = $toint;
*/
$row['tasks'][] = $r;
}
/*
$r['counter']=$totalCounter;
$r['from_interval']=$from_interval;
$r['to_interval']=$to_interval;
$r['hrname']=$name;*/
//$row['tasks'][]=$r;
} else {
/*
id_counter: "1",
id_profile: "17",
from_interval: "1519887600",
to_interval: "1519934400",
counter: "18"}
*/
/*
$fake['id_counter']=0;
$fake['id_profile']=$pr_id;
$fake['from_interval']=$sDateHour;
$fake['to_interval']=$eDateHour;
$fake['counter']=0;
$row['tasks'][]=$fake;
*/
}
$res[] = $row;
}
$temp['data'] = $res;
$fn->deconnect();
$sel->deconnect();
echo json_encode($temp, JSON_PRETTY_PRINT);
}
?>
So what is wrong with this if anyone can understand?
Is that because of mysql or because of the php?
Related
I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.
I use mysqli API to query a large table, every 1000 rows, but the memory of my server grows up very fast. The memory is 0, even the swap. I don't know how to fix it.
The table has 4 million rows so I query the table each time by 1000.
Here is my code:
<?php
ini_set('memory_limit','32M');
$config = require_once('config.php');
$attachmentRoot = $config['attachment_root'];
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
echo "\nRename The Dup Files With Suffix: .es201704111728es \n";
$startTime = microtime(true);
/**
*
* Move dup file to $name + .es201704111728es
*/
$suffix = ".es201704111728es";
$fileLinesLimit = 100000;
$listSuffix = 0;
$lines = 0;
/**
* Create File List.
*/
$fileList = '/tmp/Dupfilelist.txt';
$baseListName = $fileList.$listSuffix;
//$fs = fopen($baseListName,'w');
$totalSize = 0;
$start = 0;
$step = 10000;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
while($result->num_rows > 0)
{
while($result->fetch_row())
{
/*$fiepath = $row[1];
$uniqueIdsArray = array_unique(explode(',',$row[2]));if(empty($row[3]))throw new \Exception("\n".'ERROR:'.$row[0]."\n".var_export($row[3],true)."\n");
$uniqueFilesArray = array_unique(explode(',',$row[3]));
$hasFile = array_search($fiepath,$uniqueFilesArray);
if($hasFile !== false)
unset($uniqueFilesArray[$hasFile]);
$num = count($uniqueIdsArray);
$fileNum = count($uniqueFilesArray);
$ids = implode(',',$uniqueIdsArray);
if($num>1 && $fileNum>0){
//echo "\nID: $row[0] . File Need To Rename:".var_export($uniqueFilesArray,true)."\n";
$size = intval($row[4]);
if($lines >= $fileLinesLimit){
$lines = 0;
$listSuffix++;
//$fileList .= $listSuffix;
}
array_map(function($file) use ($attachmentRoot,$suffix,$fiepath,$totalSize,$size,$fileLinesLimit,&$listSuffix,&$lines,$fileList){
//$fs = fopen($fileList.$listSuffix,'a');
if($file === $fiepath)
return -1;
$source = $file;
$target = $source.$suffix;
//rename($source,$target);
//fwrite($fs,$source.','.$target."\n");
//file_put_contents($fileList.$listSuffix, $source.','.$target."\n",FILE_APPEND);
//$totalSize += intval($size);
$lines ++;
//echo memory_get_usage()."\n";
//fclose($fs);
//unset($fs);
//try to write file without amount memory cost
//$ts = fopen('/tmp/tempfile-0412','w');
},$uniqueFilesArray);
//echo "Test Just One Attachment Record.\n";
//echo "Ids:$ids\n";
//exit();
}*/
}
echo memory_get_peak_usage(true)."\n";
if(!$mysqli->ping())
{
echo "Mysql Conncect Failed.Reconnecting.\n";
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
}
//mysqli_free_result($result);
$result->close();
unset($result);
$start += $step;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
}
echo "Dup File Total Size: $totalSize\n";
echo "Script cost time :".(microtime(true)-$startTime)." ms\n";sleep(1000*10);
mysqli_close($mysqli);
exit();
I enable the XDEBUG extension.Sorry for that.
I disable this extension and everything goes well.
I ran into this issue with PHP Version 7.3.26 on Centos 7. I worked around it by using unbuffered query (instead of buffered). In the above example, replace
$result = $mysqli->query($sql)
with
$result = $mysqli->query($sql, MYSQLI_USE_RESULT)
I am using a for loop on my client's website to insert purchased ticket information into a database. The loop is working correctly, but the client has requested the option to attach a unique identifier to the first entry every time the for loop is run. This identifier would be used to highlight the primary ticket owner when the tickets are printed. I have included the current for loop below for reference. Any ideas on how to achieve this? Thank you.
$threepack = '';
$i = '';
for($i = 0; $i < $tickets; $i++)
{
$firstname = 'firstname'.$threepack;
$lastname = 'lastname'.$threepack;
$address = 'address'.$threepack;
$city = 'city'.$threepack;
$postal = 'postal'.$threepack;
$phone = 'phone'.$threepack;
$altphone = 'altphone'.$threepack;
$sec_firstname = 'sec_firstname'.$threepack;
$sec_lastname = 'sec_lastname'.$threepack;
$email = 'email'.$threepack;
$table->firstname = $data->$firstname;
$table->lastname = $data->$lastname;
$table->address = $data->$address;
$table->city = $data->$city;
$table->postal = $data->$postal;
$table->phone = $data->$phone;
$table->altphone = $data->$altphone;
$table->sec_firstname = $data->$sec_firstname;
$table->sec_lastname = $data->$sec_lastname;
$table->email = $data->$email;
$table->id = 0;
$table->order_total = $data->total;
$table->store();
if($data->tickets == '-1')
{
if($threepack == 2)
{
$threepack = 3;
} else {
$threepack = 2;
}
}
// 8 Fields
if($data->tickets == '5')
{
if ($threepack == '') {
$threepack = 2;
} else {
$threepack += 1;
}
}
}
for ($i = 0; $i < $tickets; $i++) {
// ...
if ($i == 0)
$table->highlightme = 1;
// ...
$table->store();
// ...
}
I'm getting this JSON result from mySQL with the following php query:
/* grab the posts from the db */
$query = "SELECT * FROM ko_timetable";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
JSON Result:
post = {
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Sunday;
ID = 19;
"ORDER_BY" = 5;
TIME = "1:00pm - 2:30pm";
};
}
{
post = {
"CLASS_LEVEL" = "General/Intermediate/Advanced";
"CLASS_TYPE" = "Muay Thai Spar - Competitive";
"DAY_OF_WEEK" = Sunday;
ID = 27;
"ORDER_BY" = 5;
TIME = "6:00pm - 9:00pm";
};
},
{
post = {
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Fighters Training";
"DAY_OF_WEEK" = Monday;
ID = 1;
"ORDER_BY" = 1;
TIME = "9:30am - 11:00pm";
};
But how can I change this query to get this result group by "DAY_OF_WEEK". See example below, thanks for your help:
{
Sunday = {
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Sunday;
ID = 19;
"ORDER_BY" = 5;
TIME = "1:00pm - 2:30pm";
};
{
"CLASS_LEVEL" = "General/Intermediate/Advanced";
"CLASS_TYPE" = "Muay Thai Spar - Competitive";
"DAY_OF_WEEK" = Sunday;
ID = 27;
"ORDER_BY" = 5;
TIME = "6:00pm - 9:00pm";
};
},
{
Monday = {
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Fighters Training";
"DAY_OF_WEEK" = Monday;
ID = 1;
"ORDER_BY" = 1;
TIME = "9:30am - 11:00pm";
};
Thanks
You can use DAY_OF_WEEK as array index like this,
while($post = mysql_fetch_assoc($result)) {
$posts[$posts["DAY_OF_WEEK"]] = array('post'=>$post);
}
But remember that in the example you have shown the indexes of array are names of the days then the result of previous Sunday will be replaced with this weeks Sunday and so on so forth.
You could also use a count variable to avoid replacing of keys with duplicate names, like this.
$count = 1;
while($post = mysql_fetch_assoc($result)) {
$posts[$posts["DAY_OF_WEEK"].$count] = array('post'=>$post);
$count++;
}
change this:
while($post = mysql_fetch_assoc($result)) {
$posts[ $post['DAY_OF_WEEK'] ] = $post;
}
I have a container rectangle and element rectangle, both are specified only in height and width. Using PHP I need to figure out what positions and orientation would allow for the most possible blits of the element within the container having absolutely no overlap.
An Example :
$container = array(5000,2000);
$element = array(300,200);
The output should be an array of "blit" arrays (or objects) like so
$blit_object = array($x,$y,$rotation_degrees);
Well, since no one is answering me, I am just going to show my "trial and error" solution in case anyone else ever needs it.
It calculates the two basic layout options and sees which one has the most and uses that.
function MakeBlits($container,$element)
{
$container_x = $container[0];
$container_y = $container[1];
$options = array();
for($i = 0;$i<=1;$i++)
{
if($i == 0)
{
$element_x = $element[0];
$element_y = $element[1];
}
else
{
$element_x = $element[1];
$element_y = $element[0];
}
$test_x = floor($container_x/$element_x);
$test_y = floor($container_y/$element_y);
$test_remainder_x = $container_x - $test_x*$element_x;
$test_remainder_y = $container_y - $test_y*$element_y;
$test_x2 = 0;
$test_x3 = 0;
$test_y2 = 0;
$test_y3 = 0;
if($test_remainder_x > $element_y)
{
$test_x2 = floor($test_remainder_x/$element_y);
$test_y2 = floor($container_y/$element_x);
}
if($test_remainder_y > $element_x)
{
$test_x3 = floor($container_x/$element_y);
$test_y3 = floor($test_remainder_y/$element_x);
}
$options[] = array(
'total'=>($test_x*$test_y)+($test_x2*$test_y2)+($test_x3*$test_y3),
'x'=>$test_x,
'y'=>$test_y,
'x2'=>$test_x2,
'y2'=>$test_y2,
'x3'=>$test_x3,
'y3'=>$test_y3
);
}
if($options[0]['total']>=$options[1]['total'])
{
$option = $options[0];
$rotate = 0;
$width = $element[0];
$height = $element[1];
}
else
{
$option = $options[1];
$rotate = -90;
$width = $element[1];
$height = $element[0];
}
$blit_objects = array();
for($i=0;$i<$option['x'];$i++)
{
for($j=0;$j<$option['y'];$j++)
{
$blit_objects[] = array(
'x'=>$i*$width,
'y'=>$j*$height,
'rotation'=>$rotate);
}
}
for($k = 0;$k < $option['x2'];$k++)
{
for($l = 0;$l < $option['y2'];$l++)
{
$blit_objects[] = array(
'x'=>$i*$width + $k*$height,
'y'=>$l*$width,
'rotation'=>$rotate+90);
}
}
for($k = 0;$k < $option['x3'];$k++)
{
for($l = 0;$l < $option['y3'];$l++)
{
$blit_objects[] = array(
'x'=>$k*$height,
'y'=>$j*$height+$l*$width,
'rotation'=>$rotate+90);
}
}
return $blit_objects;
}