Getting same data repeatedly more than multiple times(in thousands) - php

I am trying to get data in table format from database with multiple queries. I am getting the exact data but the data am getting is same data repeatedly more than thousand times. Please I need a help to fix this to get actual data not multiple data below is my code. Please have a look at it. I am not getting any error but the data am getting is multiple and repeated data.
controller:
public function getReports()
{
$records = [];
$data = [];
$data['title'] = 'test Report';
$date_type = $this->input->get('filter_options');
$course = $this->input->get('course');
$filter_options = $date_type;
$department = $this->input->get('department');
$division = $this->input->get('division');
$month = 1;
$year = date('Y');
$day = date('d');
$data['department'] = $department;
$data['course'] = $course;
$data['division'] = $division;
$data['date_type'] = $date_type;
$course_condition = ' AND 1=1 ';
if($course)
$course_condition = ' AND o.title="'.$course.'"';
$department_condition = ' AND 1=1 ';
if($department)
$department_condition = ' AND u.department="'.$department.'"';
$date_condition = ' and 1=1 ';
if($date_type==1)
{
$date_condition = ' and ta.submittimestamp BETWEEN DATE_SUB(NOW(), INTERVAL 300 DAY) AND NOW() ';
//dd($date_condition);
}
else if($date_type==2)
{
$date_condition = ' and MONTH(ta.submittimestamp) = MONTH(CURRENT_DATE())
AND YEAR(ta.submittimestamp) = YEAR(CURRENT_DATE()) ';
}
else if($date_type==3)
{
$year = $this->input->get('year');
$month = $this->input->get('month');
$date_condition = ' and YEAR(ta.submittimestamp) = "'.$year.'" and MONTH(ta.submittimestamp) = "'.$month.'" ';
}
$group_condition = "GROUP by u.usr_id";
if ($course)
$users_query="SELECT o.title as course_title,u.*,u.usr_id,o.obj_id FROM object_data o,usr_data u,obj_members rn WHERE o.obj_id=rn.obj_id AND u.usr_id=rn.usr_id AND o.type='crs' AND o.obj_id=$course";
$user_records = $this->base_model->executeSelectQuery($users_query);
$final_data = [];
foreach($user_records as $user)
{
if(!$course)
continue;
$user_course_query="SELECT *, (select obj_id FROM object_reference f WHERE e.child = f.ref_id limit 1 ) as final_reference FROM object_data a , object_data g,tree c,tree e , object_reference b ,object_reference f,object_reference d WHERE a.obj_id = b.obj_id AND b.ref_id = c.parent AND c.child = d.ref_id AND d.ref_id = e.parent AND f.obj_id = g.obj_id AND a.obj_id=$course ";
$user_course_records = $this->base_model->executeSelectQuery($user_course_query);
foreach($user_course_records as $course_data)
{
$final_reference=$course_data->final_reference;
$user_tests_query = "SELECT u.firstname,o.*,ta.*,tpr.workingtime,tcr.mark_official,(tcr.reached_points/tcr.max_points)*100 as result FROM usr_data u,object_data o,tst_active ta,tst_tests tt ,tst_pass_result tpr, tst_result_cache tcr WHERE u.usr_id=ta.user_fi AND tt.obj_fi=o.obj_id AND ta.test_fi=tt.test_id AND ta.active_id=tpr.active_fi AND tcr.active_fi=ta.active_id AND u.usr_id=$user->usr_id AND o.obj_id = $final_reference ".$date_condition;
$user_tests = $this->base_model->executeSelectQuery($user_tests_query);
foreach($user_tests as $test)
{
$dta['usr_id'] = $user->usr_id;
$dta['firstname'] = $user->firstname;
$dta['email'] = $user->email;
$dta['matriculation'] = $user->matriculation;
$dta['approve_date'] = $user->approve_date;
$dta['department'] = $user->department;
$dta['tries'] = $test->tries;
$dta['test_title'] = $test->title;
$dta['submittimestamp'] = $test->submittimestamp;
$dta['workingtime'] = $test->workingtime;
// $dta['mark_official'] = $test->mark_official;
$dta['result'] = $test->result;
if($test->mark_official=='passed')
$result_status = '<span class="label label-primary"> Passed </span>';
else if($test->mark_official=='failed')
$result_status = '<span class="label label-danger"> Failed </span>';
$dta['status'] = $result_status;
$dta['division'] = $this->udfTextData(2);
$dta['job_title'] = $this->udfTextData(6);
$final_data[] = $dta;
}
}
}
$data['records'] = $final_data;

Related

Very slow loop PHP

I'm a junior dev and i have a problem with a script's loop.
The loop cycles large array came from the DB.
The problem is complete the loop in shortest time is possible, but for now, about 500 elements it takes 15mins to finish.
It's is not acceptable.
The empty space in quotation marks is necessary for my type of file.
This is the code in private class function:
$length = count($this->fileH1);
for ($z = 0; $z < $length; $z++) {
$this->fileH2[$z]['id_paziente'] = $this->fileH1[$z]->id_paziente;
$this->fileH2[$z]['regione'] = decifra($_SESSION['cod_regione']);
$this->fileH2[$z]['asl'] = decifra($_SESSION['cod_asl']);
$this->fileH2[$z]['cod_struttura'] = decifra($_SESSION['cod_struttura']);
$this->fileH2[$z]['tipo_assist'] = "RIA";
$this->fileH2[$z]['tipo_strutt'] = decifra($_SESSION['tipo_struttura']);
// CERCO LE INFO DELLE MENOMAZIONI DEL PAZIENTE
$stmt_get_info_menomazioni = $this->centro->prepare('SELECT codice, icd9_nuovo FROM tbl_pazienti_terapie_menomazioni WHERE id_paziente = ? AND id_contratto = ? LIMIT 1');
$stmt_get_info_menomazioni->bind_param("ii", $this->fileH1[$z]->id_paziente, $this->fileH1[$z]->id_contratto); //$fileH1[$z]['id_terapia']);
$stmt_get_info_menomazioni->execute();
$stmt_get_info_menomazioni->store_result();
$stmt_get_info_menomazioni->bind_result($cod_menomazione, $icd9_menomazione);
if ($stmt_get_info_menomazioni->num_rows > 0) {
$stmt_get_info_menomazioni->fetch();
if ($cod_menomazione !== NULL || $cod_menomazione !== '')
$this->fileH2[$z]['cod_menomazione'] = $cod_menomazione;
else $this->fileH2[$z]['cod_menomazione'] = ' ';
if ($icd9_menomazione !== NULL || $icd9_menomazione !== '')
$this->fileH2[$z]['icd9_menomazione'] = str_pad($icd9_menomazione, 10, " ");
else $this->fileH2[$z]['icd9_menomazione'] = ' ';
} else {
$this->fileH2[$z]['cod_menomazione'] = ' ';
$this->fileH2[$z]['icd9_menomazione'] = ' ';
}
$stmt_get_info_menomazioni->close();
$this->fileH2[$z]['num_registro'] = $this->fileH1[$z]->anno_rif . decifra($_SESSION['cod_asl']) . '0' . date('y') . str_pad($_POST['mese'], 2, '0', STR_PAD_LEFT) . '0001';; // "203021040001"; // AGGIUNGERE numero registro struttura
$this->fileH2[$z]['medico_autorizz'] = ' ';
$this->fileH2[$z]['cod_medico_autorizz'] = ' ';
$this->fileH2[$z]['istat_primo_ricovero'] = '000000';
$this->fileH2[$z]['progressivo'] = $this->fileH1[$z]->progressivo;
// CERCO LE INFO DELLE TERAPIE DEL PAZIENTE
$stmt_get_info_menomazioni = $this->centro->prepare('SELECT data_autorizz, data_inizio, data_fine FROM tbl_pazienti_contratti WHERE id_paziente = ? AND id = ? LIMIT 1');
$stmt_get_info_menomazioni->bind_param("ii", $this->fileH1[$z]->id_paziente, $this->fileH1[$z]->id_contratto); //$fileH1[$z]['id_terapia']);
$stmt_get_info_menomazioni->execute();
$stmt_get_info_menomazioni->store_result();
$stmt_get_info_menomazioni->bind_result($data_autorizz, $data_inizio, $data_fine);
if ($stmt_get_info_menomazioni->num_rows > 0) {
$stmt_get_info_menomazioni->fetch();
if ($data_autorizz !== NULL || $data_autorizz !== '0000-00-00') $this->fileH2[$z]['data_prescrizione'] = date('dmY', strtotime($data_autorizz)); else $this->fileH2[$z]['data_prescrizione'] = ' ';
if ($data_inizio !== NULL || $data_inizio !== '0000-00-00') $this->fileH2[$z]['data_inizio_terapia'] = date('dmY', strtotime($data_inizio)); else $this->fileH2[$z]['data_inizio_terapia'] = ' ';
if ($data_fine !== NULL || $data_fine !== '0000-00-00') $this->fileH2[$z]['data_fine_terapia'] = date('dmY', strtotime($data_fine)); else $this->fileH2[$z]['data_fine_terapia'] = ' ';
// CALCOLO LE DATE DEL CICLO DI FATTURAZIONE
$data_inizio_mese_attuale = date('Y-m-1');
$data_inizio_terapia = date('Y-m-d', strtotime($data_inizio));
if ($data_inizio_mese_attuale < $data_inizio_terapia)
$this->fileH2[$z]['data_inizio_periodo_fatturazione'] = date('dmY', strtotime($data_inizio_terapia));
else $this->fileH2[$z]['data_inizio_periodo_fatturazione'] = date('dmY', strtotime($data_inizio_mese_attuale));
$data_fine_mese_attuale = date('Y-m-t'); // t = ultimo gg del mese attuale
$data_fine_terapia = date('Y-m-d', strtotime($data_fine));
if ($data_fine_mese_attuale > $data_fine_terapia)
$this->fileH2[$z]['data_fine_periodo_fatturazione'] = date('dmY', strtotime($data_fine_terapia));
else $this->fileH2[$z]['data_fine_periodo_fatturazione'] = date('dmY', strtotime($data_fine_mese_attuale));
// CALCOLO QTA PRESTAZIONI EFFETTUATE
$stmt_get_qta_prestaz_eff = $this->centro->prepare('SELECT COUNT(id) FROM tbl_pazienti_terapie_presenze WHERE MONTH(DATE(ingresso_effettuato)) = ? AND id_paziente = ?');
$stmt_get_qta_prestaz_eff->bind_param('ii', $this->mese, $this->fileH1[$z]->id_paziente);
$stmt_get_qta_prestaz_eff->execute();
$stmt_get_qta_prestaz_eff->store_result();
$stmt_get_qta_prestaz_eff->bind_result($qta_prestaz);
$stmt_get_qta_prestaz_eff->fetch();
$this->fileH2[$z]['qta_prestaz'] = str_pad($qta_prestaz, 3, "0", STR_PAD_LEFT);
$this->fileH2[$z]['codifica_nomencl'] = 't';
if ($this->fileH2[$z]['progressivo'] == '99')
$this->fileH2[$z]['codice_prestaz'] = ' ';
else $this->fileH2[$z]['codice_prestaz'] = '001.001';
$this->fileH2[$z]['esenzione_1'] = '0';
$this->fileH2[$z]['esenzione_2'] = ' ';
$this->fileH2[$z]['esenzione_3'] = '0';
$this->fileH2[$z]['onere'] = "1";
$this->fileH2[$z]['importo_compart'] = '000000,00';
$this->fileH2[$z]['posizione_compart'] = '0';
if ($this->fileH1[$z]->tariffa !== NULL || $this->fileH1[$z]->tariffa !== '')
$this->fileH2[$z]['importo_totale'] = str_replace('.', ',', str_pad(floatval($this->fileH1[$z]->tariffa) * $qta_prestaz, 9, "0", STR_PAD_LEFT));
else $this->fileH2[$z]['importo_totale'] = " ";
$stmt_get_qta_prestaz_eff->close();
}
$stmt_get_info_menomazioni->close();
$this->fileH2[$z]['posizione_contab'] = ' ';
$this->fileH2[$z]['err01'] = ' ';
$this->fileH2[$z]['err02'] = ' ';
$this->fileH2[$z]['err03'] = ' ';
$this->fileH2[$z]['err04'] = ' ';
$this->fileH2[$z]['err05'] = ' ';
$this->fileH2[$z]['err06'] = ' ';
$this->fileH2[$z]['err07'] = ' ';
$this->fileH2[$z]['err08'] = ' ';
$this->fileH2[$z]['err09'] = ' ';
$this->fileH2[$z]['err10'] = ' ';
$this->fileH2[$z]['anno_rif'] = $this->fileH1[$z]->anno_rif;
$this->fileH2[$z]['cod_strut_erog'] = decifra($_SESSION['cod_struttura_eroga']);
$this->fileH2[$z]['identificativo_mensile'] = $this->fileH1[$z]->identificativo_mensile;
$this->fileH2[$z]['anno_mese_invio'] = date('Ym');
$this->fileH2[$z]['asl_addebito'] = 000;
}
Someone can help me?
UPDATE 1:
First thanks all for the answer.
Make a unique call with JOIN and move out of loop the prepare statment. Now the time for about 500 item is 5mins.
$sql = 'SELECT COUNT(tp.id),pc.data_autorizz, pc.data_inizio, pc.data_fine, tm.codice, tm.icd9_nuovo FROM tbl_pazienti_terapie_presenze as tp LEFT JOIN tbl_pazienti_contratti as pc ON tp.id_paziente = pc.id_paziente LEFT JOIN tbl_pazienti_terapie_menomazioni as tm ON tm.id_contratto = pc.id AND tm.id_paziente = pc.id_paziente WHERE MONTH(DATE(tp.ingresso_effettuato)) = ? AND tp.id_paziente = ? AND pc.id = ?';
$do_sql = $this->centro->prepare($sql);
$length = count($this->fileH1);
for ($z = 0; $z < $length; $z++) {
$this->fileH2[$z]['id_paziente'] = $this->fileH1[$z]['id_paziente'];['id_terapia'];
$this->fileH2[$z]['regione'] = decifra($_SESSION['cod_regione']);
$this->fileH2[$z]['asl'] = decifra($_SESSION['cod_asl']);
$this->fileH2[$z]['cod_struttura'] = decifra($_SESSION['cod_struttura']);
$this->fileH2[$z]['tipo_assist'] = "RIA";
$this->fileH2[$z]['tipo_strutt'] = decifra($_SESSION['tipo_struttura']);
$do_sql->bind_param('iii', $this->mese, $this->fileH1[$z]['id_paziente'], $this->fileH1[$z]['id_contratto']);
$do_sql->execute();
$do_sql->store_result();
$do_sql->bind_result($qta_prestaz, $data_autorizz, $data_inizio, $data_fine, $cod_menomazione, $icd9_menomazione);
if ($do_sql->num_rows > 0) {
$do_sql->fetch();
if ($cod_menomazione !== NULL && $cod_menomazione !== '')
$this->fileH2[$z]['cod_menomazione'] = $cod_menomazione;
else $this->fileH2[$z]['cod_menomazione'] = ' ';
if ($icd9_menomazione !== NULL && $icd9_menomazione !== '')
$this->fileH2[$z]['icd9_menomazione'] = str_pad($icd9_menomazione, 10, " ");
else $this->fileH2[$z]['icd9_menomazione'] = ' ';
if ($data_autorizz !== NULL && $data_autorizz !== '0000-00-00') $this->fileH2[$z]['data_prescrizione'] = date('dmY', strtotime($data_autorizz)); else $this->fileH2[$z]['data_prescrizione'] = ' ';
if ($data_inizio !== NULL && $data_inizio !== '0000-00-00') $this->fileH2[$z]['data_inizio_terapia'] = date('dmY', strtotime($data_inizio)); else $this->fileH2[$z]['data_inizio_terapia'] = ' ';
if ($data_fine !== NULL && $data_fine !== '0000-00-00') $this->fileH2[$z]['data_fine_terapia'] = date('dmY', strtotime($data_fine)); else $this->fileH2[$z]['data_fine_terapia'] = ' ';
if ($this->fileH1[$z]['tariffa'] !== NULL || $this->fileH1[$z]['tariffa'] !== '')
$this->fileH2[$z]['importo_totale'] = str_replace('.', ',', str_pad(floatval($this->fileH1[$z]->tariffa) * $qta_prestaz, 9, "0", STR_PAD_LEFT));
else $this->fileH2[$z]['importo_totale'] = ' ';
$this->fileH2[$z]['codifica_nomencl'] = 't';
if ($this->fileH2[$z]['progressivo'] == '99')
$this->fileH2[$z]['codice_prestaz'] = ' ';
else $this->fileH2[$z]['codice_prestaz'] = '001.001';
$this->fileH2[$z]['esenzione_1'] = '0';
$this->fileH2[$z]['esenzione_2'] = ' ';
$this->fileH2[$z]['esenzione_3'] = '0';
$this->fileH2[$z]['onere'] = "1";
$this->fileH2[$z]['importo_compart'] = '000000,00';
$this->fileH2[$z]['posizione_compart'] = '0';
// CALCOLO LE DATE DEL CICLO DI FATTURAZIONE
$data_inizio_mese_attuale = date('Y-m-1');
$data_inizio_terapia = date('Y-m-d', strtotime($data_inizio));
if ($data_inizio_mese_attuale < $data_inizio_terapia)
$this->fileH2[$z]['data_inizio_periodo_fatturazione'] = date('dmY', strtotime($data_inizio_terapia));
else $this->fileH2[$z]['data_inizio_periodo_fatturazione'] = date('dmY', strtotime($data_inizio_mese_attuale));
$data_fine_mese_attuale = date('Y-m-t'); // t = ultimo gg del mese attuale
$data_fine_terapia = date('Y-m-d', strtotime($data_fine));
if ($data_fine_mese_attuale > $data_fine_terapia)
$this->fileH2[$z]['data_fine_periodo_fatturazione'] = date('dmY', strtotime($data_fine_terapia));
else $this->fileH2[$z]['data_fine_periodo_fatturazione'] = date('dmY', strtotime($data_fine_mese_attuale));
$this->fileH2[$z]['num_registro'] = $this->fileH1[$z]['anno_rif'] . decifra($_SESSION['cod_asl']) . '0' . date('y') . str_pad($_POST['mese'], 2, '0', STR_PAD_LEFT) . '0001';; // "203021040001"; // AGGIUNGERE numero registro struttura
$this->fileH2[$z]['medico_autorizz'] = ' ';
$this->fileH2[$z]['cod_medico_autorizz'] = ' ';
$this->fileH2[$z]['istat_primo_ricovero'] = '000000';
$this->fileH2[$z]['progressivo'] = $this->fileH1[$z]['progressivo'];
}
$this->fileH2[$z]['posizione_contab'] = ' ';
$this->fileH2[$z]['err01'] = ' ';
$this->fileH2[$z]['err02'] = ' ';
$this->fileH2[$z]['err03'] = ' ';
$this->fileH2[$z]['err04'] = ' ';
$this->fileH2[$z]['err05'] = ' ';
$this->fileH2[$z]['err06'] = ' ';
$this->fileH2[$z]['err07'] = ' ';
$this->fileH2[$z]['err08'] = ' ';
$this->fileH2[$z]['err09'] = ' ';
$this->fileH2[$z]['err10'] = ' ';
$this->fileH2[$z]['anno_rif'] = $this->fileH1[$z]['anno_rif'];
$this->fileH2[$z]['cod_strut_erog'] = decifra($_SESSION['cod_struttura_eroga']);
$this->fileH2[$z]['identificativo_mensile'] = $this->fileH1[$z]['identificativo_mensile'];
$this->fileH2[$z]['anno_mese_invio'] = date('Ym');
$this->fileH2[$z]['asl_addebito'] = 000;
$do_sql->close();
better than before but still not acceptable
UPDATE 2:
After some testing i found that this query COUNT(id) FROM tbl_pazienti_terapie_presenze WHERE MONTH(ingresso_effettuato) = ? AND id_paziente = ? causes the severe slowdown. I have no idea why this happens.
SOLUTION:
Thanks all for the answer.
The problem is the query function MONTH(). Although the field is indexed, the function MONTH() skips the index and consequently slows down the query.
Replacing it with
e.g.
WHERE ingresso_effettuato BETWEEN '2021-12-01 00:00:00', '2021-12-31 23:59:59'
or
WHERE ingresso_effettuato >= '2021-12-01 00:00:00' AND ingresso_effettuato <= '2021-12-31 23:59:59' the problem is fixed.
There are mulitple Reasons why your code might be slow.
In PHP it is often caused by misusing the Database. First of all you need setup indexes on your tables, especially for the fields which youre using for your SELECT statement.
Also since PHP have to connect to a database over a network, your code might be slower if your database is on different server than your webserver ist. Some Hosting Providers use different networks for Databases. Because of this it is crutial to make as less calls to the database as possible.
In your script i saw that you use prepare(), execute(), close() and this 3 times. Which means that you go to the database and execute some actions there. This might lead to slower performance as well.
I made a little performance test to show that there is a difference between using preapre statement within a loop and ouside:
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$mysqli = new mysqli('db','db','db','db');
$queries = 100;
$start = microtime(true);
$resultId = null;
$resultTest = null;
for($i=0;$i<=100;$i++){
$id = 1;
$sql = "SELECT id,test FROM test WHERE id = ?";
$statement = $mysqli->prepare($sql);
$statement->bind_param('i',$id);
$statement->execute();
$statement->store_result();
$statement->bind_result($resultId,$resultTest);
$statement->close();
$id = 2;
$sql = "SELECT id,test FROM test WHERE id = ?";
$statement = $mysqli->prepare($sql);
$statement->bind_param('i',$id);
$statement->execute();
$statement->store_result();
$statement->bind_result($resultId,$resultTest);
$statement->close();
$id = 3;
$sql = "SELECT id,test FROM test WHERE id = ?";
$statement = $mysqli->prepare($sql);
$statement->bind_param('i',$id);
$statement->execute();
$statement->store_result();
$statement->bind_result($resultId,$resultTest);
$statement->close();
}
$end = microtime(true);
$diff = $end-$start;
echo "Prepare statements inside loop time: ".$diff."<br/>";
$start = microtime(true);
$sql = "SELECT id,test FROM test WHERE id = ?";
$statement1 = $mysqli->prepare($sql);
$statement2 = $mysqli->prepare($sql);
$statement3 = $mysqli->prepare($sql);
for($i=0;$i<=100;$i++){
$id = 1;
$statement1->bind_param('i',$id);
$statement1->execute();
$statement1->store_result();
$statement1->bind_result($resultId,$resultTest);
$id = 2;
$statement2->bind_param('i',$id);
$statement2->execute();
$statement2->store_result();
$statement2->bind_result($resultId,$resultTest);
$id = 3;
$statement3->bind_param('i',$id);
$statement3->execute();
$statement3->store_result();
$statement3->bind_result($resultId,$resultTest);
}
$statement1->close();
$statement2->close();
$statement3->close();
$end = microtime(true);
$diff = $end-$start;
echo "Prepare statements only execute time: ".$diff."<br/>";
Results are
Prepare statements inside loop time: 0.046118021011353
Prepare statements only execute time: 0.020095109939575
So i would suggest in first place to move your statements outside of the loop, then check your indexes.
To do so. You can write down one of your SQL Queries with Real values and execute your SELECT statement with a DESCRIBE in PHPMyadmin
e.g.
DESCRIBE SELECT COUNT(id) FROM tbl_pazienti_terapie_presenze WHERE MONTH(DATE(ingresso_effettuato)) = 12 AND id_paziente = 1336
in the Result you will see if there are indexes used or not, if not then you need to created the index for this field.
And often the SQL queries can be combined with a join since you reuse the ID in 3 differnt SQL queries the Tables must somehow to be relateable so they might be able to be joined together to one statement.
Iam not sure if this answer will fix your speed problem but at least you have some clues where you can optimize.

get data from mysql with multiple value

I have some data in url
sub_cat.php?s=1&os=3,1&brand=10,9&camera=19&storage=15,13&data=17
I have:
operating systems with id 3 and 1
brands with id 10 and 9
camera with id 19
storage with id 15 and 13
data with id 17
i want to show mobiles having these specifications from sql database
if (isset($_GET['brand'])) {
$sf_brand = $_GET['brand'];
$brand_split = explode(',', $sf_brand);
$sf_brand_len = count($brand_split);
for ($ab=0; $ab < $sf_brand_len; $ab++) {
$append_sf_brand .= 'OR product.product_brand LIKE \''.$brand_split[$ab].'\' ';
}
$append_sf_brand_f = '('.substr($append_sf_brand, 3).')';
}else{
$append_sf_brand_f = '';
}
if (isset($_GET['os'])) {
$sf_os = $_GET['os'];
$os_split = explode(',', $sf_os);
$sf_os_len = count($os_split);
for ($ao=0; $ao < $sf_os_len; $ao++) {
$append_sf_os .= 'OR productspec.prospec_expspec_id LIKE \''.$os_split[$ao].'\' ';
}
$append_sf_os_f = '('.substr($append_sf_os, 3).')';
}else{
$append_sf_os_f = '';
}
if (isset($_GET['camera'])) {
$sf_camera = $_GET['camera'];
$camera_split = explode(',', $sf_camera);
$sf_camera_len = count($camera_split);
for ($ac=0; $ac < $sf_camera_len; $ac++) {
$append_sf_camera .= 'OR productspec.prospec_expspec_id LIKE \''.$camera_split[$ac].'\' ';
}
$append_sf_camera_f = '('.substr($append_sf_camera, 3).')';
}else{
$append_sf_camera_f = '';
}
if (isset($_GET['data'])) {
$sf_data = $_GET['data'];
$data_split = explode(',', $sf_data);
$sf_data_len = count($data_split);
for ($ad=0; $ad < $sf_data_len; $ad++) {
$append_sf_data .= 'OR productspec.prospec_expspec_id LIKE \''.$data_split[$ad].'\' ';
}
$append_sf_data_f = '('.substr($append_sf_data, 3).')';
}else{
$append_sf_data_f = '';
}
if (isset($_GET['storage'])) {
$sf_storage = $_GET['storage'];
$storage_split = explode(',', $sf_storage);
$sf_storage_len = count($storage_split);
for ($as=0; $as < $sf_storage_len; $as++) {
$append_sf_storage .= 'OR productspec.prospec_expspec_id LIKE \''.$storage_split[$as].'\' ';
}
$append_sf_storage_f = '('.substr($append_sf_storage, 3).')';
}else{
$append_sf_storage_f = '';
}
$sf_condition = '(product.product_id LIKE productspec.prospec_product_id) AND '.$append_sf_brand_f.' AND '.$append_sf_os_f.' AND '.$append_sf_camera_f.' AND '.$append_sf_data_f.' AND '.$append_sf_storage_f;
I have query:
$get_brand_query = mysqli_query($connect, "SELECT * FROM product, productspec WHERE $sf_condition");
But it is not working well, so how I can show mobiles can anyone help me thanks.

Codeigniter pagination error after searching

After searching data when i click on next page then it doesn't work with searching results. After click it goes on first page. How can i solve this problem ?
Thank you
Controller:
public function gkclientsadd(){
$arg["src"] = 0;
$arg["pageOffset"] = 0;
$np = $this->uri->segment(3);
$data["offset"] = 0;
$this->search_by = 0;
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
if(isset($_GET["client_search"]))
{
$arg["login"] = $this->input->get('login');
$arg["pwd"] = $this->input->get('pwd');
$arg["basetariff"] = $this->input->get("basetariff");
$arg["crc"] = $this->input->get("crc");
$arg["resone"] = $this->input->get("resone");
$arg["rpp"] = $this->default_rpp;
$arg["offset"] = $this->default_offset;
$arg["src"] = 1;
$this->search_basetariff = $arg["basetariff"];
$this->search_currency = $arg["crc"];
$this->search_parent = $arg["resone"];
$this->search_by = 1;
//print_r($arg);die;
} else $arg["src"] = 0;
}
if(!empty($np)){
$arg["pageOffset"] = ($np/$this->default_rpp);
$arg["rpp"] = $this->default_rpp;
$arg["offset"] = ($this->default_rpp)*$arg["pageOffset"];
$data["offset"] = $arg["offset"];
$arg["src"] = 1;
}
$data["gkclientsData"] = $this->admin_model->getGkclients($this->userId, $this->rtc_table,$arg, $this->default_rpp, $this->default_offset);
$data["getTotalGk"] = $this->admin_model->getTotalGk($this->rtc_table,$arg);
$data["totalRecords"] = count($data["getTotalGk"]);
$data["totalPage"] = $data["totalRecords"]/$this->default_rpp;
$data["Page"] = $arg["pageOffset"]+1;
$config = array();
$config["base_url"] = base_url() . "index.php/admin/gkclientsadd";
$config["total_rows"] = $data["totalRecords"] ;
$config["per_page"] = $this->default_rpp;
$config["uri_segment"] = 3;
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["links"] = $this->pagination->create_links();
$this->load->view('admin/clients/gkclientsadd',$data);
}
Model:
public function getGkclients($userId, $rtc_table,$arg, $default_rpp,$default_offset)
{
$this->load->database();
if($arg['src']== 1){
$whr = "";
$rpp = "";
$offset = "";
if(!empty($arg["rpp"])) $rpp .= " LIMIT ".$arg["rpp"]."";
if(!empty($arg["offset"])) $offset .= " OFFSET ".$arg["offset"]."";
if(!empty($arg["login"])) $whr .= " AND $rtc_table.login = '".$arg["login"]."'";
if(!empty($arg["pwd"])) $whr .= " AND $rtc_table.password = '".$arg["pwd"]."'";
if(!empty($arg["basetariff"])) $whr .= " AND $rtc_table.id_tariff = '".$arg["basetariff"]."'";
if(!empty($arg["crc"])) $whr .= " AND $rtc_table.id_currency = '".$arg["crc"]."'";
if(!empty($arg["resone"])) $whr .= " AND $rtc_table.id_res = '".$arg["resone"]."'";
} else {
$whr="";
$rpp= "Limit $default_rpp";
$offset= "OFFSET $default_offset";
}
$query = "SELECT DISTINCT $rtc_table.id_client,$rtc_table.id_res,$rtc_table.login,$rtc_table.password,$rtc_table.id_tariff,
$rtc_table.account_state,$rtc_table.type,$rtc_table.type2,currency_names.name
FROM $rtc_table, currency_names
WHERE currency_names.id = $rtc_table.id_currency $whr
order by $rtc_table.login ASC $rpp $offset";
$query_result = $this->db->query($query);
$gkData=$query_result->result();
return $gkData;
}
http://i.stack.imgur.com/yMa6d.jpg

how to break it into function

I have some 'else if' cases in a page. Now I want to make only a single function so that code length may be shorten.
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
//////********Below code is repeated in this page **************///////
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
//////********Till Here, code is repeated in this page **************///////
}
please tell my how can i break above code into another function so that I can save my code length from same code repetition.
you mean something like this?
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
_insert($resultArr);
}
function _insert($resultArr){
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
}

modify a query of a joomla module

i have a module which executes two functions. the first filters and showsthe latest comments per category. the second one filters and shows the top commenters of all categories. i want to hack it in order to show the top commenters per category. for the first one there is in the backend the option to select category but for the top commenters there is not.
here is the code of the module. forgive me for its length.
class modK2CommentsHelper
{
public static function getLatestComments(&$params)
{
$mainframe = JFactory::getApplication();
$limit = $params->get('comments_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$cid = $params->get('category_id', NULL);
$jnow = JFactory::getDate();
$now = K2_JVERSION != '15' ? $jnow->toSql() : $jnow->toMySQL();
$nullDate = $db->getNullDate();
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
$query = "SELECT c.*, i.catid, i.title, i.alias, category.alias as catalias, category.name as categoryname
FROM #__k2_comments as c
LEFT JOIN #__k2_items as i ON i.id=c.itemID
LEFT JOIN #__k2_categories as category ON category.id=i.catid
WHERE i.published=1
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND i.access<={$aid} ";
}
$query .= " AND category.published=1 AND category.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND category.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND category.access<={$aid} ";
}
$query .= " AND c.published=1 ";
if ($params->get('catfilter'))
{
if (!is_null($cid))
{
if (is_array($cid))
{
JArrayHelper::toInteger($cid);
$query .= " AND i.catid IN(".implode(',', $cid).")";
}
else
{
$query .= " AND i.catid=".(int)$cid;
}
}
}
if (K2_JVERSION != '15')
{
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND category.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
}
$query .= " ORDER BY c.commentDate DESC ";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('commentDateFormat') == 'relative')
{
$config = JFactory::getConfig();
$now = new JDate();
if (K2_JVERSION == '30')
{
$tzoffset = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
$now->setTimezone($tzoffset);
}
else
{
$tzoffset = $config->getValue('config.offset');
$now->setOffset($tzoffset);
}
$created = new JDate($row->commentDate);
$diff = $now->toUnix() - $created->toUnix();
$dayDiff = floor($diff / 86400);
if ($dayDiff == 0)
{
if ($diff < 5)
{
$row->commentDate = JText::_('K2_JUST_NOW');
}
elseif ($diff < 60)
{
$row->commentDate = $diff.' '.JText::_('K2_SECONDS_AGO');
}
elseif ($diff < 120)
{
$row->commentDate = JText::_('K2_1_MINUTE_AGO');
}
elseif ($diff < 3600)
{
$row->commentDate = floor($diff / 60).' '.JText::_('K2_MINUTES_AGO');
}
elseif ($diff < 7200)
{
$row->commentDate = JText::_('K2_1_HOUR_AGO');
}
elseif ($diff < 86400)
{
$row->commentDate = floor($diff / 3600).' '.JText::_('K2_HOURS_AGO');
}
}
}
$row->commentText = K2HelperUtilities::wordLimit($row->commentText, $params->get('comments_word_limit'));
$row->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->commentText);
$row->itemLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($row->itemID.':'.urlencode($row->alias), $row->catid.':'.urlencode($row->catalias))));
$row->link = $row->itemLink."#comment{$row->id}";
$row->catLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($row->catid.':'.urlencode($row->catalias))));
if ($row->userID > 0)
{
$row->userLink = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
$getExistingUser = JFactory::getUser($row->userID);
$row->userUsername = $getExistingUser->username;
}
else
{
$row->userUsername = $row->userName;
}
// Switch between commenter name and username
if ($params->get('commenterName', 1) == 2)
$row->userName = $row->userUsername;
$row->userImage = '';
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
$comments[] = $row;
}
return $comments;
}
}
public static function getTopCommenters(&$params)
{
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
$limit = $params->get('commenters_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$query = "SELECT COUNT(id) as counter, userName, userID, commentEmail FROM #__k2_comments WHERE userID > 0 AND published = 1 GROUP BY userID ORDER BY counter DESC";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
if (count($rows))
{
foreach ($rows as $row)
{
if ($row->counter > 0)
{
$row->link = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
if ($params->get('commenterNameOrUsername', 1) == 2)
{
$getExistingUser = JFactory::getUser($row->userID);
$row->userName = $getExistingUser->username;
}
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
if ($params->get('commenterLatestComment'))
{
$query = "SELECT * FROM #__k2_comments WHERE userID = ".(int)$row->userID." AND published = 1 ORDER BY commentDate DESC";
$db->setQuery($query, 0, 1);
$comment = $db->loadObject();
$item = JTable::getInstance('K2Item', 'Table');
$item->load($comment->itemID);
$category = JTable::getInstance('K2Category', 'Table');
$category->load($item->catid);
$row->latestCommentText = $comment->commentText;
$row->latestCommentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->latestCommentText);
$row->latestCommentLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($category->alias))))."#comment{$comment->id}";
$row->latestCommentDate = $comment->commentDate;
}
$commenters[] = $row;
}
}
if (isset($commenters))
return $commenters;
}
}
}
every help is appreciated. thank you very much

Categories