Hello im using codeigniter and this controller file for cronjob but somehow public function fiveminutes work and gives response(ok) but public function daily doesn’t work and no responses or errors it should give “ok daily” response can someone help please ?? i couldn’t solve this
Hope someone fan help me because its realy important for me and my users
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Cronjob extends Guess_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['m_admin', 'm_cronjob', 'm_leaderboard']);
}
public function fiveminutes()
{
if (time() >= $this->data['settings']['leaderboard_date']) {
$topClaimer = $this->m_leaderboard->getTopClaimer($this->data['settings']['admin_username']);
$topReferral = $this->m_leaderboard->getTopReferral($this->data['settings']['admin_username']);
$topFaucet = $this->m_leaderboard->getTopFaucet($this->data['settings']['admin_username']);
$topShortlink = $this->m_leaderboard->getTopShortlink($this->data['settings']['admin_username']);
$topOfferwall = $this->m_leaderboard->getTopOfferwall($this->data['settings']['admin_username']);
$activityRewards = explode('|', $this->data['settings']['activity_contest_reward']);
$referralRewards = explode('|', $this->data['settings']['referral_contest_reward']);
$faucetRewards = explode('|', $this->data['settings']['faucet_contest_reward']);
$shortlinkRewards = explode('|', $this->data['settings']['shortlink_contest_reward']);
$offerwallRewards = explode('|', $this->data['settings']['offerwall_contest_reward']);
$nextTime = (date("Y-m-d", strtotime('Sunday')) == date("Y-m-d", time())) ? strtotime('Sunday') + 7 * 86400 : strtotime('Sunday');
$this->m_cronjob->updateLeaderboardDate($nextTime);
$this->m_cronjob->resetLeaderboard();
$this->cache->delete('leaderboard_info');
if (!empty($this->data['settings']['activity_contest_reward'])) {
for ($i = 0; $i < min(count($activityRewards), count($topClaimer)); ++$i) {
$this->m_core->addNotification($topClaimer[$i]['id'], currency($activityRewards[$i], $this->data['settings']['currency_rate']) . " from Activity Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topClaimer[$i]['id'], trim($activityRewards[$i]));
$this->m_core->addOtherLog($topClaimer[$i]['id'], 'Activity contest #' . ($i + 1), trim($activityRewards[$i]));
}
}
if (!empty($this->data['settings']['referral_contest_reward'])) {
for ($i = 0; $i < min(count($referralRewards), count($topReferral)); ++$i) {
$this->m_core->addNotification($topReferral[$i]['id'], currency($referralRewards[$i], $this->data['settings']['currency_rate']) . " from Referral Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topReferral[$i]['id'], trim($referralRewards[$i]));
$this->m_core->addOtherLog($topReferral[$i]['id'], 'Referral contest #' . ($i + 1), trim($referralRewards[$i]));
}
}
if (!empty($this->data['settings']['faucet_contest_reward'])) {
for ($i = 0; $i < min(count($faucetRewards), count($topFaucet)); ++$i) {
$this->m_core->addNotification($topFaucet[$i]['id'], currency($faucetRewards[$i], $this->data['settings']['currency_rate']) . " from Faucet Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topFaucet[$i]['id'], trim($faucetRewards[$i]));
$this->m_core->addOtherLog($topFaucet[$i]['id'], 'Faucet contest #' . ($i + 1), trim($faucetRewards[$i]));
}
}
if (!empty($this->data['settings']['shortlink_contest_reward'])) {
for ($i = 0; $i < min(count($shortlinkRewards), count($topShortlink)); ++$i) {
$this->m_core->addNotification($topShortlink[$i]['id'], currency($shortlinkRewards[$i], $this->data['settings']['currency_rate']) . " from Shortlink Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topShortlink[$i]['id'], trim($shortlinkRewards[$i]));
$this->m_core->addOtherLog($topShortlink[$i]['id'], 'Shortlink contest #' . ($i + 1), trim($shortlinkRewards[$i]));
}
}
if (!empty($this->data['settings']['offerwall_contest_reward'])) {
for ($i = 0; $i < min(count($offerwallRewards), count($topOfferwall)); ++$i) {
$this->m_core->addNotification($topOfferwall[$i]['id'], currency($offerwallRewards[$i], $this->data['settings']['currency_rate']) . " from Offerwall Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topOfferwall[$i]['id'], trim($offerwallRewards[$i]));
$this->m_core->addOtherLog($topOfferwall[$i]['id'], 'Offerwall contest #' . ($i + 1), trim($offerwallRewards[$i]));
}
}
echo 'ok 1';
}
if ($this->data['settings']['lottery_duration'] > 0) {
if (time() >= $this->data['settings']['lottery_date']) {
$lotteries = $this->m_cronjob->getAllLottery();
if (count($lotteries) > 0) {
$luckyNumber = rand(0, count($lotteries) - 1);
$reward = count($lotteries) * $this->data['settings']['lottery_reward'] + $this->data['settings']['lottery_base_reward'];
$this->m_cronjob->updateUserBalance($lotteries[$luckyNumber]['user_id'], $reward);
$this->m_cronjob->insertLotteryHistory($lotteries[$luckyNumber]['user_id'], $lotteries[$luckyNumber]['number'], $reward);
$user = $this->m_core->get_user_from_id($lotteries[$luckyNumber]['user_id']);
$this->m_core->addNotification($user['id'], currency($reward, $this->data['settings']['currency_rate']) . " from Lottery was credited to your balance.", 1);
$this->m_core->addOtherLog($user['id'], 'Lottery', $reward);
}
$this->m_cronjob->updateLotteryDate(time() + 86400 * $this->data['settings']['lottery_duration']);
$this->m_cronjob->resetLottery();
echo 'ok 2';
}
}
$offerHistory = $this->m_cronjob->getAvailableOffers();
foreach ($offerHistory as $history) {
$this->m_cronjob->updateUserBalance($history['user_id'], $history['amount']);
$this->m_cronjob->updateOfferwallHistoryStatus($history['id']);
$user = $this->m_core->get_user_from_id($history['user_id']);
$this->m_core->addExp($user['id'], $this->data['settings']['offerwall_exp_reward']);
$user['exp'] += $this->data['settings']['offerwall_exp_reward'];
if ($user['exp'] >= ($user['level'] + 1) * 100) {
$this->m_core->levelUp($user['id']);
}
}
echo 'ok 3';
$currencies = $this->m_cronjob->getCurrencyName();
$currencyName = [];
foreach ($currencies as $currency) {
array_push($currencyName, $currency['currency_name']);
}
if (!in_array("bitcoin", $currencyName)) {
array_push($currencyName, 'bitcoin');
}
$query = urlencode(implode(',', $currencyName));
$apiUrl = 'https://api.coingecko.com/api/v3/simple/price?ids=' . $query . '&vs_currencies=usd';
$result = #json_decode(get_data($apiUrl), TRUE);
foreach ($result as $name => $price) {
$this->m_cronjob->updatePrice($name, $price['usd']);
}
if (isset($result['bitcoin']) && isset($result['bitcoin']['usd'])) {
$this->m_cronjob->updateBtcPrice($result['bitcoin']['usd']);
}
echo 'ok 4';
}
public function daily()
{
$yesterday = strtotime('yesterday midnight');
$today = strtotime('today midnight');
$date = date("Y-m-d", strtotime('yesterday midnight'));
$todayData = [
'date' => date("Y-m-d", $today)
];
$yesterdayData = [
'date' => $date
];
if ($this->m_cronjob->isYesterdayExist($date)) {
$this->db->insert('faucet_stats', $yesterdayData);
}
if ($this->m_cronjob->checkYesterdayLog($date)) {
$yesterdayData['active_users'] = $this->m_cronjob->countActiveUsers($yesterday, $today);
$yesterdayData['new_users'] = $this->m_cronjob->countNewUsers($yesterday, $today);
$faucetStat = $this->m_cronjob->faucetStat($yesterday, $today);
$yesterdayData['faucet_count'] = $faucetStat['cnt'];
$yesterdayData['faucet_amount'] = $faucetStat['amount'];
$shortlinkStat = $this->m_cronjob->shortlinkStat($yesterday, $today);
$yesterdayData['shortlink_count'] = $shortlinkStat['cnt'];
$yesterdayData['shortlink_amount'] = $shortlinkStat['amount'];
$offerwallStat = $this->m_cronjob->offerwallStat($yesterday, $today);
$yesterdayData['offerwall_count'] = $offerwallStat['cnt'];
$yesterdayData['offerwall_amount'] = $offerwallStat['amount'];
$offerwallStat = $this->m_cronjob->ptcStat($yesterday, $today);
$yesterdayData['ptc_count'] = $offerwallStat['cnt'];
$yesterdayData['ptc_amount'] = $offerwallStat['amount'];
$diceStat = $this->m_cronjob->diceStat($yesterday, $today);
$yesterdayData['dice_count'] = $diceStat['cnt'];
$yesterdayData['dice_amount'] = $diceStat['amount'];
$depositStat = $this->m_cronjob->depositStat($yesterday, $today);
$yesterdayData['deposit_count'] = $depositStat['cnt'];
$yesterdayData['deposit_amount'] = $depositStat['amount'];
$depositStat = $this->m_cronjob->withdrawStat($yesterday, $today);
$yesterdayData['withdraw_count'] = $depositStat['cnt'];
$yesterdayData['withdraw_amount'] = $depositStat['amount'];
$coinflipStat = $this->m_cronjob->coinflipStat($yesterday, $today);
$yesterdayData['coinflip_count'] = $coinflipStat['cnt'];
$yesterdayData['coinflip_amount'] = $coinflipStat['amount'];
$achievementStat = $this->m_cronjob->achievementStat($yesterday, $today);
$yesterdayData['achievement_count'] = $achievementStat['cnt'];
$yesterdayData['achievement_amount'] = $achievementStat['amount'];
$wheelStat = $this->m_cronjob->wheelStat($yesterday, $today);
$yesterdayData['wheel_count'] = $wheelStat['cnt'];
$yesterdayData['wheel_amount'] = $wheelStat['amount'];
$this->db->set('active_users', $yesterdayData['active_users']);
$this->db->set('new_users', $yesterdayData['new_users']);
$this->db->set('faucet_count', $yesterdayData['faucet_count']);
$this->db->set('faucet_amount', $yesterdayData['faucet_amount']);
$this->db->set('shortlink_count', $yesterdayData['shortlink_count']);
$this->db->set('shortlink_amount', $yesterdayData['shortlink_amount']);
$this->db->set('ptc_count', $yesterdayData['ptc_count']);
$this->db->set('ptc_amount', $yesterdayData['ptc_amount']);
$this->db->set('offerwall_count', $yesterdayData['offerwall_count']);
$this->db->set('offerwall_amount', $yesterdayData['offerwall_amount']);
$this->db->set('dice_count', $yesterdayData['dice_count']);
$this->db->set('dice_amount', $yesterdayData['dice_amount']);
$this->db->set('coinflip_count', $yesterdayData['coinflip_count']);
$this->db->set('coinflip_amount', $yesterdayData['coinflip_amount']);
$this->db->set('achievement_count', $yesterdayData['achievement_count']);
$this->db->set('achievement_amount', $yesterdayData['achievement_amount']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('deposit_count', $yesterdayData['deposit_count']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('withdraw_amount', $yesterdayData['withdraw_amount']);
$this->db->set('wheel_amount', $yesterdayData['wheel_amount']);
$this->db->set('wheel_count', $yesterdayData['wheel_count']);
$this->db->set('is_done', 1);
$this->db->where('date', $date);
$this->db->update('faucet_stats');
$this->db->insert('faucet_stats', $todayData);
$this->m_cronjob->clearHistory();
$this->db->set('wheel_cnt', 0);
$this->db->set('today_faucet', 0);
$this->db->update('users');
echo 'ok daily';
}
}
}
Most likely this function
if($this->m_cronjob->checkYesterdayLog($date))
results to false. I recommend that you should test this first.
if($this->m_cronjob->checkYesterdayLog($date)){
echo 'okay daily';
}else{
echo 'not okay, daily';
}
You can also check if the cronjob actually calls the daily function.
Related
I would appreciate some guidance on the following issue. I am by no means an expert in php. The code below takes almost 10 seconds to execute! Is there anything I am doing that is wrong or bad practice?
$data = [];
$today = date("Y/m/d");
$ThisYear = Date('Y'); //get current Year
$ThisMonth = Date('m'); //get current month
$Tday = '01'; //first day of month
$Tmonth = '09'; //September
if (8 < $ThisMonth && $ThisMonth < 13) {
$AcYear = $ThisYear; }
else {
$AcYear = $ThisYear - 1; // sets start of academic year to be last year
}
$AcFullYear = $AcYear.'/'.$Tmonth.'/'.$Tday;
//find rank in all school
$students_rank = [];
$school_id = Student::model()->findByAttributes(['user_master_id' => Yii::app()->user->id])->school_master_id;
$criteria1 = new CDbCriteria;
$criteria1->with = array('user');
$criteria1->condition = "t.school_master_id=:school_master AND user.status ='1'";
$criteria1->params = array(':school_master' => $school_id);
$school_students_details = Student::model()->findAll($criteria1);
foreach ($school_students_details as $key => $value) {
$student_name = StudentDetails::model()->findByAttributes(['user_master_id' => $value->user_master_id]); //student details with year group
$criteria2 = new CDbCriteria;
$criteria2->with = array('homeworkMaster');
$criteria2->condition = "t.student_id=:student_id AND homeworkMaster.question_type_id<>:question_type_id";
$criteria2->params = array(':student_id' => $value->user_master_id, ':question_type_id' => 6);
$HW_assignment_track = HomeworkAssignmentTrack::model()->findAll($criteria2);
$total_HW = count((array)$HW_assignment_track);
$student_score = 0;
$student_rank = 0;
$student_total_score = 0;
$total_HW_marks = 0;
$under_deadline_HW = 0;
$criteria3 = new CDbCriteria();
$criteria3->condition = "student_id =:student_id AND status=:status AND created_at >= '$AcFullYear' AND created_at <= '$today'";
$criteria3->params = [':student_id' => $value->user_master_id, ':status' => 2];
$student_completed_HW = HomeworkStudentAnswere::model()->findAll($criteria3);
$i = 1;
foreach ($student_completed_HW as $s_c_h_K => $s_c_h_V) {
if ($s_c_h_V->homework->homework_type == 2) {
$total_HW -= 1;
} elseif ($s_c_h_V->homework->homework_type == 1) {
$HW_questions = HomeworkQuestion::model()->findAllByAttributes(['homework_master_id' => $s_c_h_V->homework_id, 'status' => 1]);
foreach ($HW_questions as $qKey => $qVal) {
if ($qVal->question_type_id ==3) {
$total_HW_marks += 2;
} else {
$total_HW_marks += $qVal->marks;
}
}
$assignment = HomeworkAssignmentTrack::model()->findByAttributes(['id' => $s_c_h_V->assignment_track_id]);
$homeworks_within_validate = Assignment::model()->findByPk($assignment->assignment_id);
if ($homeworks_within_validate->valid_date === '0' && $homeworks_within_validate->deadline >= date('Y-m-d')) {
$total_HW -= 1;
}
if ($homeworks_within_validate->valid_date === '1' || (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($s_c_h_V->created_at))) && ($homeworks_within_validate->deadline < date('Y-m-d')))) {
if ($s_c_h_V->review_status === '2') {
$student_total_score += $s_c_h_V->score;
}
}
$homework_submit = HomeworkCompleteNotification::model()->findByAttributes(['homework_id' => $s_c_h_V->homework_id, 'assignment_track_id' => $s_c_h_V->assignment_track_id, 'student_id' => $value->user_master_id]);
if (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($homework_submit->created_at))) && ($s_c_h_V->review_status === '2')) {
$under_deadline_HW += 10;
}
if ($total_HW_marks !=0) {
$student_score += round(($student_total_score / $total_HW_marks) * 100);
} else {
$student_score = 0;
}
}
$i += 1;
}
//add revision scores to rank score
$criteria4 = new CDbCriteria();
$criteria4->condition = "user_id =:user_id AND date_created >= '$AcFullYear' AND date_created <= '$today'";
$criteria4->params = [':user_id' => $value->user_master_id];
$revision_score = RevisionScores::model()->findAll($criteria4);
$sum = 0;
foreach($revision_score as $item) {
$sum += $item['score'];
} //end of adding revision scores
$students_rank[$key]['student_id'] = $value->user_master_id;
$students_rank[$key]['year_group'] = $student_name->year_group_id; //added year group to model array
if ($student_score > 0) {
$student_rank += round($student_score / $total_HW, 0) + $under_deadline_HW;
$students_rank[$key]['rank'] = $student_rank + $sum;
} else {
$students_rank[$key]['rank'] = $sum;
}
}
$model = $this->multid_sort($students_rank, 'rank');
$rank_score = round(array_column($model, 'rank', 'student_id')[Yii::app()->user->id],0);
$year_rank =[];
$current_st = StudentDetails::model()->findByAttributes(['user_master_id' => Yii::app()->user->id]);
$current_st_year = $current_st->year_group_id;
$rank_list = [];
foreach ($model as $key => $value) {
$rank_list[] = $value['student_id'];
if ($value['year_group'] == $current_st_year) {
$year_rank[] = $value['student_id'];
}
}
$user = Yii::app()->user->id;
$sch_position = array_search($user,$rank_list);
$yr_position = array_search($user,$year_rank);
$final_rank = $sch_position + 1;
$yr_rank = $yr_position + 1;
$sch_rank = $final_rank;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($sch_rank %100) >= 11 && ($sch_rank%100) <= 13) {
$sc_abbreviation = 'th';
$yr_abbreviation = 'th';
} else {
$sc_abbreviation = $ends[$sch_rank % 10];
$yr_abbreviation = $ends[$yr_rank % 10];
}
$models = UserMaster::model()->findByPk(Yii::app()->user->id);
$year_name = $models->studentDetails->yearGroup->name;
$data['type'] = 'success';
$data['score'] = '<div>Ranking Score: '.$rank_score.'</div>';
$data['yr_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$yr_rank. '</span><sup class="script-top" id="year_rank_abb">' .$yr_abbreviation. '</sup></div><div id="year_name">In ' .$year_name. '</div>';
$data['school_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$sch_rank. '</span><sup class="script-top" id="year_rank_abb">' .$sc_abbreviation. '</sup></div><div id="year_name">In School</div>';
$data['rank_revise'] ='<div>'.$rank_score.'</div>';
$data['yr_rank_revise'] = '<span>'.$yr_rank.'</span><sup class="superscript" style="left:0">'.$yr_abbreviation.'</sup>';
$data['sch_rank_revise'] = '<span>'.$sch_rank.'</span><sup class="superscript" style="left:0">'.$sc_abbreviation.'</sup>';
$_SESSION['rank'] = $rank_score;
$_SESSION['accuracy'] = $rank_score;
echo json_encode($data);
exit;
The above is used in an Yii application. It runs perfectly fine on localhost, but on live site, takes over 10 seconds to execute.
Your help and guidance is appreciated.
Thank
I got this simple foreach loop and can't figure out where is the problem with counter.
I get results like this. I am trying to make counter enlarged for one if it meets the conditions.
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id[$row['sifra']] = $row;
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = ${$i++} = $value['sifra'];
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}
Where am I wrong?
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT 80"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id = $row['sifra'];
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = $i++;
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}
The following code works as expected to get the number of patients per age group.
It also gets the highest (or most common) age group.
$count_0_19 = 0;
$count_20_29 = 0;
$count_30_39 = 0;
$count_40_49 = 0;
$count_50_59 = 0;
$count_above_60 = 0;
$curr_year = date('Y');
$sql= "SELECT pt_dob FROM ptlist WHERE mid=$userID";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $pdo->query($sql);
$pt_dob = $row[ 'pt_dob' ];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$pt_dob = explode('-', $row['pt_dob']);
$year = $pt_dob[0];
$month = $pt_dob[1];
$day = $pt_dob
$temp = abs($curr_year - $year);
if($temp >= 0 && $temp <= 19) {
$count_0_19++;
}
elseif($temp >= 20 && $temp <= 29) {
$count_20_29++;
}
elseif($temp >= 30 && $temp <= 39) {
$count_30_39++;
}
elseif($temp >= 40 && $temp <= 49) {
$count_40_49++;
}
elseif($temp >= 50 && $temp <= 59) {
$count_50_59++;
}
else {
$count_above_60++;
}
}
echo '0-19: '.$count_0_19.'<br>';
echo '20-29: '.$count_20_29.'<br>';
echo '30-39: '.$count_30_39.'<br>';
echo '40-49: '.$count_40_49.'<br>'; // example output is > 40-49: 7 (i.e. 7 patients in age group 40-49)
echo '50-59: '.$count_50_59.'<br>';
echo '60+: '.$count_above_60.'<br>';
// getting highest value
$a = array($count_0_19, $count_20_29, $count_30_39, $count_40_49, $count_50_59, $count_above_60);
$res = 0;
foreach($a as $v) {
if($res < $v)
$res = $v;
}
echo $res;
^^ This tells me that e.g. 9 patients are in the 30-39 age group - i.e. the highest number of patients are in this age group.
But $res gives me only the number (e.g. 9).
What I am asking your help with is to get $res to give me the text(or label) "30-39", instead of the number 9.
Please help.
continue from comment... you need to store $key into a variable.
$a = array('0-19'=>$count_0_19, '20-29'=>$count_20_29, '30-39'=>$count_30_39, '40-49'=>$count_40_49, '50-59'=>$count_50_59, '60+'=>$count_above_60);
$res = 0;
$label = '';
foreach($a as $key => $v) {
if($res < $v){
$res = $v;
$label = $key; //get label from key and store in a variable
}
}
echo 'label = '.$label . ' , Number = '.$res;
You can archived this by creating the array of labels and then incrementing it according and then find the greatest value form the $label array to get the key.
$label = [
"0_19" => 0,
"20_29" => 0,
"30_39" => 0,
"40_49" => 0,
"50_59" => 0,
"above_60" => 0,
];
while ($row4 = $result4->fetch(PDO::FETCH_ASSOC)) {
$pt_dob = explode('-', $row4['pt_dob']);
$year = $pt_dob[0];
$month = $pt_dob[1];
$day = $pt_dob$temp = abs($curr_year - $year);
if ($temp >= 0 && $temp <= 19) {
$label['0_19'] = $label['0_19'] +1;
}
elseif ($temp >= 20 && $temp <= 29) {
$label['20_29'] = $label['20_29'] +1;
}
elseif ($temp >= 30 && $temp <= 39) {
$label['30_39'] = $label['30_39']+1;
}
elseif ($temp >= 40 && $temp <= 49) {
$label['40_49'] = $label['40_49'] +1;
}
elseif ($temp >= 50 && $temp <= 59) {
$label['50_59'] = $label['50_59']+1;
}
else {
$label['above_60']= $label['above_60']+1;
}
}
echo $maxs = array_keys($label, max($label));
echo "<br/>";
foreach($label as $k => $v);
echo "key $k count $v <br/>";
When my code is moved from local server to live server it shows an error like this :
Fatal error: Call to undefined method DateTime::diff()
Code:
<?php
date_default_timezone_set('Asia/Calcutta');
$sFinalDate = date('Y-m-d', strtotime($sDate));
$sNow = new DateTime();
$iRemain = new DateTime( $sFinalDate.$sTime);
$iInterval = $iRemain->diff($sNow);
$sTimeCounter = $iInterval->format("%h: %i :%s ");
$sCalculate = $iInterval->format("%a:%h:%i");
?>
Though I found a number of people who ran into the issue of 5.2 and
lower not supporting this function, I was unable to find any solid
examples to get around it. Therefore I hope this can help some others:
<?php
function get_timespan_string($older, $newer) {
$Y1 = $older->format('Y');
$Y2 = $newer->format('Y');
$Y = $Y2 - $Y1;
$m1 = $older->format('m');
$m2 = $newer->format('m');
$m = $m2 - $m1;
$d1 = $older->format('d');
$d2 = $newer->format('d');
$d = $d2 - $d1;
$H1 = $older->format('H');
$H2 = $newer->format('H');
$H = $H2 - $H1;
$i1 = $older->format('i');
$i2 = $newer->format('i');
$i = $i2 - $i1;
$s1 = $older->format('s');
$s2 = $newer->format('s');
$s = $s2 - $s1;
if($s < 0) {
$i = $i -1;
$s = $s + 60;
}
if($i < 0) {
$H = $H - 1;
$i = $i + 60;
}
if($H < 0) {
$d = $d - 1;
$H = $H + 24;
}
if($d < 0) {
$m = $m - 1;
$d = $d + get_days_for_previous_month($m2, $Y2);
}
if($m < 0) {
$Y = $Y - 1;
$m = $m + 12;
}
$timespan_string = create_timespan_string($Y, $m, $d, $H, $i, $s);
return $timespan_string;
}
function get_days_for_previous_month($current_month, $current_year) {
$previous_month = $current_month - 1;
if($current_month == 1) {
$current_year = $current_year - 1; //going from January to previous December
$previous_month = 12;
}
if($previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4) {
return 30;
}
else if($previous_month == 2) {
if(($current_year % 4) == 0) { //remainder 0 for leap years
return 29;
}
else {
return 28;
}
}
else {
return 31;
}
}
function create_timespan_string($Y, $m, $d, $H, $i, $s)
{
$timespan_string = '';
$found_first_diff = false;
if($Y >= 1) {
$found_first_diff = true;
$timespan_string .= pluralize($Y, 'year').' ';
}
if($m >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($m, 'month').' ';
}
if($d >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($d, 'day').' ';
}
if($H >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($H, 'hour').' ';
}
if($i >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($i, 'minute').' ';
}
if($found_first_diff) {
$timespan_string .= 'and ';
}
$timespan_string .= pluralize($s, 'second');
return $timespan_string;
}
function pluralize( $count, $text )
{
return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}
?>
source http://php.net/manual/en/function.date-diff.php
if you using php 5.3 then there would be another issue
working above example on php>=5.3
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 7 years ago.
I have the below function, But when I run the code make error like:
Fatal error: Using $this when not in object context in E:....
How to fix it. I replace $this-> with self:: but it failed too.
Please help in this regards,
<?php
function cehck_files()
{
$file1 = 'C:\xampp\htdocs\test\test1.php';
$file2 = 'C:\xampp\htdocs\test\test2.php';
$test = $this->compareFiles($file1,$file2,true);
$test_display = $this->toTable($test);
echo "<pre>";
print_r($test_display);
print_r($test);
echo "</pre>";
}
function compareFiles($file1, $file2, $compareCharacters = false) {
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
}
function compare($string1, $string2, $compareCharacters = false) {
$start = 0;
if ($compareCharacters){
$sequence1 = $string1;
$sequence2 = $string2;
$end1 = strlen($string1) - 1;
$end2 = strlen($string2) - 1;
} else {
$sequence1 = preg_split('/\R/', $string1);
$sequence2 = preg_split('/\R/', $string2);
$end1 = count($sequence1) - 1;
$end2 = count($sequence2) - 1;
}
// skip any common prefix
while ($start <= $end1 && $start <= $end2 && $sequence1[$start] == $sequence2[$start]) {
$start ++;
}
// skip any common suffix
while ($end1 >= $start && $end2 >= $start && $sequence1[$end1] == $sequence2[$end2]) {
$end1 --;
$end2 --;
}
// compute the table of longest common subsequence lengths
$table = self::computeTable($sequence1, $sequence2, $start, $end1, $end2);
// generate the partial diff
$partialDiff =
self::generatePartialDiff($table, $sequence1, $sequence2, $start);
// generate the full diff
$diff = array();
for ($index = 0; $index < $start; $index ++){
$diff[] = array($sequence1[$index], UNMODIFIED);
}
while (count($partialDiff) > 0) $diff[] = array_pop($partialDiff);
for ($index = $end1 + 1; $index < ($compareCharacters ? strlen($sequence1) : count($sequence1)); $index ++) {
$diff[] = array($sequence1[$index], UNMODIFIED);
}
// return the diff
return $diff;
}
function computeTable($sequence1, $sequence2, $start, $end1, $end2) {
$length1 = $end1 - $start + 1;
$length2 = $end2 - $start + 1;
// initialise the table
$table = array(array_fill(0, $length2 + 1, 0));
// loop over the rows
for ($index1 = 1; $index1 <= $length1; $index1 ++) {
// create the new row
$table[$index1] = array(0);
// loop over the columns
for ($index2 = 1; $index2 <= $length2; $index2 ++){
// store the longest common subsequence length
if ($sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
$table[$index1][$index2] = $table[$index1 - 1][$index2 - 1] + 1;
} else {
$table[$index1][$index2] =
max($table[$index1 - 1][$index2], $table[$index1][$index2 - 1]);
}
}
}
// return the table
return $table;
}
function generatePartialDiff( $table, $sequence1, $sequence2, $start ) {
$diff = array();
// initialise the indices
$index1 = count($table) - 1;
$index2 = count($table[0]) - 1;
// loop until there are no items remaining in either sequence
while ($index1 > 0 || $index2 > 0){
// check what has happened to the items at these indices
if ($index1 > 0 && $index2 > 0 && $sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], UNMODIFIED);
$index1 --;
$index2 --;
} elseif ($index2 > 0 && $table[$index1][$index2] == $table[$index1][$index2 - 1]) {
// update the diff and the indices
$diff[] = array($sequence2[$index2 + $start - 1], INSERTED);
$index2 --;
}else{
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], DELETED);
$index1 --;
}
}
// return the diff
return $diff;
}
function toTable($diff, $indentation = '', $separator = '<br>') {
$html = $indentation . "<table class=\"diff\">\n";
// loop over the lines in the diff
$index = 0;
while ($index < count($diff)){
// determine the line type
switch ($diff[$index][1]){
// display the content on the left and right
case UNMODIFIED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, UNMODIFIED);
$rightCell = $leftCell;
break;
// display the deleted on the left and inserted content on the right
case DELETED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, DELETED);
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
// display the inserted content on the right
case INSERTED:
$leftCell = '';
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
}
// extend the HTML with the new row
$html .=
$indentation
. " <tr>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($leftCell == '' ? 'Blank' : 'Deleted'))
. '">'
. $leftCell
. "</td>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($rightCell == '' ? 'Blank' : 'Inserted'))
. '">'
. $rightCell
. "</td>\n"
. $indentation
. " </tr>\n";
}
// return the HTML
return $html . $indentation . "</table>\n";
}
?>
You are using $this for a function which is not a method of any class.
Instead of
$test = $this->compareFiles($file1,$file2,true);
Use:
$test = compareFiles($file1,$file2,true);
Also, change
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
To
return compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
And to the remaining changes in this way.