Why is my SQL query for months and year so slow? - php

I have about 4000 dates in my database table. From this data I would need the total count that has the same month and year in an array with year and the month and total result. The array must look like this: $ year ['year'] [strftime ('% Y', $ application ['crdate'])] ['month'] [$ i] = intval ($ application ['erg']);
Rendered like that example:
[year, month jan (01), month feb (02), ...]
With data:
[2016, 0, 0, 0, 4, 0, 9, 0, 0, 0, 0, 0, 2]
I have the following code to do this, but it needs to load forever with 4000 records. Why is it so slow and how can I speed it up?
$year = array();
$where_month = false;
if($this->request->hasArgument('time')) {
$von = $this->request->getArgument('time')['von'];
$bis = $this->request->getArgument('time')['bis'];
$von_jahr = strftime('%Y',strtotime($von));
$bis_jahr = strftime('%Y',strtotime($bis));
$von_englisch_format = strftime('%Y-%m-%d',strtotime($von));
$bis_englisch_format = strftime('%Y-%m-%d',strtotime($bis));
$von_stamp = strtotime($von);
$bis_stamp = strtotime($bis);
$where_month = true;
}
for($i = 1; $i <= 12; $i++) {
if ($i <= 9) {
$i = '0' . $i;
}
$select_fields = 'T1.*';
$from_table = ' datas T1';
if($where_month) {
$where_clause = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") >= "'.$von_jahr.'" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") <= "'.$bis_jahr.'"';
} else {
$where_clause = '';
}
$groupBy = '';
$orderBy = 'crdate ASC';
$limit = '';
$erg = 0;
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
foreach($result as $bewerbung) {
$year['jahr'][strftime('%Y', $bewerbung['crdate'])]['monat'][$i] = 0;
$select_fields = '*, count(*) AS erg';
$from_table = ' datas T1';
if($where_month == false) {
$where_clause = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") = "' . strftime('%Y', $bewerbung['crdate']) . '" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "' . $i . '"';
} else {
$where_clause = '(DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y-%m-%d") BETWEEN "'.$von_englisch_format.'" AND "'.$bis_englisch_format.'") AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") = "' . strftime('%Y', $bewerbung['crdate']) . '" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "' . $i . '"';
}
$groupBy = '';
$orderBy = 'crdate ASC';
$limit = '';
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
foreach ($result as $bewerbung) {
if (intval($bewerbung['erg']) >= 1) {
$year['jahr'][strftime('%Y', $bewerbung['crdate'])]['monat'][$i] = intval($bewerbung['erg']);
}
}
}
}

my new solution looks like this:
$select_fields = 'T1.*, DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") AS "jahr",
COUNT( CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "01"
THEN 1
ELSE NULL
END
) AS "januar",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "02"
THEN 1
ELSE NULL
END
) AS "februar",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "03"
THEN 1
ELSE NULL
END
) AS "maerz",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "04"
THEN 1
ELSE NULL
END
) AS "april",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "05"
THEN 1
ELSE NULL
END
) AS "mai",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "06"
THEN 1
ELSE NULL
END
) AS "juni",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "07"
THEN 1
ELSE NULL
END
) AS "juli",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "08"
THEN 1
ELSE NULL
END
) AS "august",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "09"
THEN 1
ELSE NULL
END
) AS "september",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "10"
THEN 1
ELSE NULL
END
) AS "oktober",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "11"
THEN 1
ELSE NULL
END
) AS "november",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "12"
THEN 1
ELSE NULL
END
) AS "dezember"';
$from_table = ' tx_lemmbewerberportal_domain_model_bewerbungen T1';
$where_clause = '';
$groupBy = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y")';
$orderBy = 'crdate ASC';
$limit = '';
$erg = 0;
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
$i = 0;
foreach ($result as $row) {
$year[$i]['jahr'] = $row['jahr'];
$year[$i]['01'] = $row['januar'];
$year[$i]['02'] = $row['februar'];
$year[$i]['03'] = $row['maerz'];
$year[$i]['04'] = $row['april'];
$year[$i]['05'] = $row['mai'];
$year[$i]['06'] = $row['juni'];
$year[$i]['07'] = $row['juli'];
$year[$i]['08'] = $row['august'];
$year[$i]['09'] = $row['september'];
$year[$i]['10'] = $row['oktober'];
$year[$i]['11'] = $row['november'];
$year[$i]['12'] = $row['dezember'];
$i++;
}
return $year;
Within a second, the data is loaded. Thank you anyway. :-)

Related

Days of Stay counter with php

I'm a little stuck on my homework. I'm doing a hospital days counter,
The time, day, month and year of entry are recorded, as well as a possible exit with day month and year.
The program needs to calculate the days of stay each month and charge them per month whether the month of stay has been completed or not.
I am very very stuck I hope you can help me, I am just learning.
Is in scriptcase php and is oriented to an event:
$f = {folio};
//fechasdeentrada
$check_sql3 = "SELECT id FROM HabitaAct WHERE folio = ".$f;
sc_lookup(ds_3, $check_sql3 );
$id1 = {ds_3[0][0]};
$check_sql4 = "SELECT diae FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_4, $check_sql4 );
$diae = {ds_4[0][0]}; // day
$check_sql2 = "SELECT mese FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_2, $check_sql2 );
$mese = {ds_2[0][0]}; // month
$check_sql5 = "SELECT Ane FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_5, $check_sql5 );
$Ane = {ds_5[0][0]}; // year
$check_sql6 = "SELECT tieme FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_6, $check_sql6 );
$tieme = {ds_6[0][0]}; // time
//exit date
$check_sql7 = "SELECT diaS FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_7, $check_sql7 );
$diaS = {ds_7[0][0]}; //day
$check_sql8 = "SELECT mesS FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_8, $check_sql8 );
$mesS = {ds_8[0][0]}; //month
$check_sql9 = "SELECT AnS FROM HabitaAct WHERE id = '".$id1."' ";
sc_lookup(ds_9, $check_sql9 );
$AnS = {ds_9[0][0]}; // year
$dientr = $diae;
$anac = $Ane;
$vd =$diae;
$ma = $mese;
$aa= $Ane;
$an = $Ane;
$limanu = 12;
if( $mesS == $mese ){
if($AnS==$Ane){
$dmeig = $diaS - $diae;
echo $dmeig;
if($diae=0){
$diae=1;
}
echo $diae;
}
}else{
for (; ; ) {
if( $ma == 1 ){ $limitedemes= 31; }
if( $ma == 2 ){ $limitedemes= 28; }
if( $ma == 3 ){ $limitedemes= 31; }
if( $ma == 4 ){ $limitedemes= 30;}
if( $ma == 5 ){ $limitedemes= 31;}
if( $ma == 6 ){$limitedemes= 30;}
if( $ma == 7 ){ $limitedemes= 31;}
if( $ma == 8 ){ $limitedemes= 31;}
if( $ma == 9 ){ $limitedemes= 30;}
if( $ma == 10 ){ $limitedemes= 31;}
if( $ma == 11 ){ $limitedemes= 30;}
if( $ma == 12 ){ $limitedemes=31;}
if($ma == $mesS ){
if( $aa == $AnS ){
$limanu = $mesS;
$ma = 1;
}else{
$limanu = $mesS;
}
}else{
$limanu = 12;
}
$contadordedias = $limitedemes - $vd;
echo "<br> ".$vd." dias totales ".$contadordedias;
echo "<br> mes actual ".$ma;
$man = $ma;
$ma = $man+1;
$vd = 0;
echo "<br> set 0 ".$vd;
if ($ma > $limanu || $ma = 12 ) {
$ma = 1;
$an = $aa + 1;
echo "<br> año ".$aa;
if ($aa > $AnS ) {
if($ma = $mesS ){
echo "dias mes final".$diaS;
break;
}
}
}
}
}

Why does this code take a long time to execute?

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

Cannot use object of type MysqlResultSet

i had a problem in php install.php file
Cannot use object of type MysqlResultSet
i dont know why is my code not working
and this is my code
$this->provider->executeQuery('INSERT INTO perfect SET type="kings", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players['name'], $get_players['email'], 0, date('Y.m.d'))
);
any idea ?
full code is
public function _isperfect()
{
// attackers
$count_attackers = 0;
$attackers_points = 0;
$attackers = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='attackers' ORDER BY points DESC LIMIT 3");
while ( $attackers->next( ) )
{
$attackers_points = $attackers->row['points'];
$count_attackers++;
}
if($count_attackers < 3)
{
$attackers_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, attack_points FROM p_players WHERE attack_points > %s', array($attackers_points));
while ( $get_players->next( ) )
{
$get_att = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='attackers' && email='". $get_players->row['email'] ."'");
if($get_att != NULL && $get_att['points'] < $get_players->row['attack_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="attackers" && email="'. $get_players->row['email'] .'"');
}
if($get_att['points'] < $get_players->row['attack_points'] || $get_att == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="attackers", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['attack_points'], date('Y.m.d'))
);
}
}
$att = 0;
$attack = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='attackers' ORDER BY points DESC LIMIT 3");
while ( $attack->next( ) )
{
$att = $attack->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="attackers"', array($att));
// end attackers
// defenders
$count_defenders = 0;
$defenders_points = 0;
$defenders = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='defenders' ORDER BY points DESC LIMIT 3");
while ( $defenders->next( ) )
{
$defenders_points = $defenders->row['points'];
$defenders_points++;
}
if($count_defenders < 3)
{
$defenders_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, defense_points FROM p_players WHERE defense_points > %s', array($defenders_points));
while ( $get_players->next( ) )
{
$get_def = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='defenders' && email='". $get_players->row['email'] ."'");
if($get_def != NULL && $get_def['points'] < $get_players->row['defense_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="defenders" && email="'. $get_players->row['email'] .'"');
}
if($get_def['points'] < $get_players->row['defense_points'] || $get_def == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="defenders", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['defense_points'], date('Y.m.d'))
);
}
}
$def = 0;
$defend = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='defenders' ORDER BY points DESC LIMIT 3");
while ( $defend->next( ) )
{
$def = $defend->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="defenders"', array($def));
// end defenders
// empires
$count_empires = 0;
$empires_points = 0;
$empires = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='empires' ORDER BY points DESC LIMIT 3");
while ( $empires->next( ) )
{
$empires_points = $empires->row['points'];
$count_empires++;
}
if($count_empires < 3)
{
$empires_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, total_people_count FROM p_players WHERE total_people_count > %s', array($empires_points));
while ( $get_players->next( ) )
{
$get_emp = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='empires' && email='". $get_players->row['email'] ."'");
if($get_emp != NULL && $get_emp['points'] < $get_players->row['total_people_count'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="empires" && email="'. $get_players->row['email'] .'"');
}
if($get_emp['points'] < $get_players->row['total_people_count'] || $get_emp == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="empires", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['total_people_count'], date('Y.m.d'))
);
}
}
$emp = 0;
$empir = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='empires' ORDER BY points DESC LIMIT 3");
while ( $empir->next( ) )
{
$emp = $empir->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="empires"', array($emp));
// end empires
// looters
$count_looters = 0;
$looters_points = 0;
$looters = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='looters' ORDER BY points DESC LIMIT 3");
while ( $looters->next( ) )
{
$looters_points = $looters->row['points'];
$count_looters++;
}
if($count_looters < 3)
{
$looters_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, thief_points FROM p_players WHERE thief_points > %s', array($looters_points));
while ( $get_players->next( ) )
{
$get_loo = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='looters' && email='". $get_players->row['email'] ."'");
if($get_loo != NULL && $get_loo['points'] < $get_players->row['thief_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="looters" && email="'. $get_players->row['email'] .'"');
}
if($get_loo['points'] < $get_players->row['thief_points'] || $get_loo == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="looters", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['thief_points'], date('Y.m.d'))
);
}
}
$loo = 0;
$loote = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='looters' ORDER BY points DESC LIMIT 3");
while ( $loote->next( ) )
{
$loo = $loote->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="looters"', array($loo));
// end looters
// kings
$end_server = $this->provider->fetchRow( "SELECT win_pid, game_over FROM `g_settings`");
$end_server_player = $this->provider->fetchRow( 'SELECT `name`,`email` FROM `p_players` WHERE id='.$end_server['win_pid'].' ');
if($end_server_player != null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="kings", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players['name'], $get_players['email'], 0, date('Y.m.d'))
);
}
}

SQL: Unix Timestamp entrys with Zero

i misunderstand why my query gives me entrys with an Timestamp of 0. Can anyone say me what im doing wrong?
Query:
SELECT
*
FROM
`changes`
WHERE
`time_from`>=1393628400
AND
`time_to`<=1394838000
AND
`area`='USERNAME'
ORDER BY
`time_from` DESC,
`time_to` DESC
PHP
$time_from = (isset($_POST['time_from']) ? strtotime($_POST['time_from']) : null);
$time_to = (isset($_POST['time_to']) ? strtotime($_POST['time_to']) : null);
if(empty($time_from) && empty($time_to)) {
/* Do Nothing */
} else {
if(!empty($time_from) && $time_from > 0 && !empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_from`>=%d AND `time_to`<=%d', $time_from, $time_to);
} else if(!empty($time_from) && $time_from > 0) {
$query = sprintf(' `time_from`>=%d', $time_from);
} else if(!empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_to`<=%d', $time_to);
}
$results = $wpdb->get_row(sprintf('SELECT COUNT(*) AS `count` FROM `%sarea_changes` WHERE%s AND `area`=\'%s\'', $wpdb->prefix, $query, $user->user_login));
$count = $results->count;
if($count < 10) {
$position = 0;
$has_more_pages = false;
}
$pages = ceil($count / $max_rows);
$query = sprintf('SELECT * FROM `%sarea_changes` WHERE%s AND `area`=\'%s\' ORDER BY `time_from` DESC, `time_to` DESC', $wpdb->prefix, $query, $user->user_login, $position, $max_rows);
print $query;
$entrys = $wpdb->get_results($query); // LIMIT %d, %d
}
POST Data:
time_from is 01.03.2014 and time_to is 15.03.2014
But i get following entrys (see the time_to), why is that 0 that dont match my Query?
Screenshot:
(Hidden data for privacy policy)

Help building a simple SQL query in Zend

My SQL query is based on data provided.
For example :
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array( 'column1', 'column2', 'column3' );
// query
$select = $table->select();
$select->where('deleted = ?', '0' );
for( $i = 0; $i < count( $columns ); $i++ ) {
if( $i == 0 ) {
$select->where( $columns[$i] . ' > ?', '0' );
} else {
$select->orWhere( $columns[$i] . ' > ?', '0' );
}
}
$select->where('disabled = ?', '0' );
// print query
echo $select->assemble();die();
Above code result into following query:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND
(disabled = '0')
But I want something like this:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0' OR column2 > '0' OR column3 > '0') AND
(disabled = '0')
How it is possible ?
Thanks
I think this should do the job:
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array('column1', 'column2', 'column3');
// query
$select = $table->select();
$select->where('deleted = ?', '0');
$myOrParts = array();
for ($i = 0; $i < count($columns); $i++) {
$myOrParts []= $table->getAdapter()->quoteInto($columns[$i] . ' > ?', '0');
}
$myWhere = implode(' OR ', $myOrParts);
$select->where(new Zend_Db_Expr($myWhere));
$select->where('disabled = ?', '0');
// print query
echo $select->assemble();
die();

Categories