PHP Building of MySQL Query String from Passed Variables - php

I have a HTML search which is passing variables via $_GET to a PHP which uses these passed variables to build a query string. The problem I am facing is building a query string that may only contain one search criteria or it may contain multiple. If only one criterion is used for the search then there is no need for an "AND" statement in the query. If there are multiple criteria used then "AND" will be needed between each criteria. How can one handle this "AND" related problem?
<?php
$IKfield01 = (isset($_GET['field01']) ? $_GET['field01'] : null);
$IKfield02 = (isset($_GET['field02']) ? $_GET['field02'] : null);
$IKfield03 = (isset($_GET['field03']) ? $_GET['field03'] : null);
$IKfield04 = (isset($_GET['field04']) ? $_GET['field04'] : null);
$IKfield05 = (isset($_GET['field05']) ? $_GET['field05'] : null);
$IKfield06 = (isset($_GET['field06']) ? $_GET['field06'] : null);
$IKfield07 = (isset($_GET['field07']) ? $_GET['field07'] : null);
$IKfield08 = (isset($_GET['field08']) ? $_GET['field08'] : null);
$IKfield09 = (isset($_GET['field09']) ? $_GET['field09'] : null);
$IKfield10 = (isset($_GET['field10']) ? $_GET['field10'] : null);
$searchfield01 = mysqli_real_escape_string($mysqli,$IKfield01);
$searchfield02 = mysqli_real_escape_string($mysqli,$IKfield02);
$searchfield03 = mysqli_real_escape_string($mysqli,$IKfield03);
$searchfield04 = mysqli_real_escape_string($mysqli,$IKfield04);
$searchfield05 = mysqli_real_escape_string($mysqli,$IKfield05);
$searchfield06 = mysqli_real_escape_string($mysqli,$IKfield06);
$searchfield07 = mysqli_real_escape_string($mysqli,$IKfield07);
$searchfield08 = mysqli_real_escape_string($mysqli,$IKfield08);
$searchfield09 = mysqli_real_escape_string($mysqli,$IKfield09);
$searchfield10 = mysqli_real_escape_string($mysqli,$IKfield10);
$prequery = "SELECT * FROM table WHERE";
$prequery1 = "";
$prequery2 = "";
$prequery3 = "";
$prequery4 = "";
$prequery5 = "";
$prequery6 = "";
$prequery7 = "";
$prequery8 = "";
$prequery9 = "";
$prequery10 = "";
$prequery11 = "";
$prequery12 = " LIMIT $maxsearch";
if ($searchfield01 != '') $prequery2 = "genus LIKE '%$searchfield01%'";
if ($searchfield02 != '') $prequery3 = "AND specificEpithet LIKE '%$searchfield02%'";
if ($searchfield03 != '') $prequery4 = "AND stateProvince LIKE '%$searchfield03%'";
if ($searchfield04 != '') $prequery5 = "AND county LIKE '%$searchfield04%'";
if ($searchfield05 != '') $prequery6= "AND family LIKE '%$searchfield05%'";
if ($searchfield06 != '') $prequery7 = "AND locality LIKE '%$searchfield06%'";
if ($searchfield07 != '') $prequery8 = "AND OtherCatalogNumbers LIKE '%$searchfield07%'";
if ($searchfield08 != '') $prequery9 = "AND recordedBy LIKE '%$searchfield08%'";
if ($searchfield09 != '') $prequery10 = "AND recordNumber LIKE '$searchfield09'";
if ($searchfield10 != '') $prequery11 = "AND catalogNumber LIKE '%$searchfield10%'";
$query = "$prequery $prequery2 $prequery3 $prequery4 $prequery5 $prequery6 $prequery7 $prequery8 $prequery9 $prequery10 $prequery11 $prequery12";
$row_count = 0;
$result = mysql_query($query) or die("MS-Query Error in select-query");
$querystats=mysql_num_rows($result);
$resultcounter=1;
while ($row = mysql_fetch_array($result))
{
$IKdfield01 = "$row[field01]";
$IKdfield02 = "$row[field02]";
$IKdfield03 = "$row[field03]";
$IKdfield04 = "$row[field04]";
$IKdfield05 = "$row[field05]";
$IKdfield06 = "$row[field06]";
$IKdfield07 = "$row[field07]";
$IKdfield08 = "$row[field08]";
$IKdfield09 = "$row[field09]";
$IKdfield10 = "$row[field10]";
$IKdfield11 = "$row[field11]";
$IKdfield12 = "$row[field12]";
$IKdfield13 = "$row[field13]";
$IKdfield14 = "$row[field14]";
$IKdfield15 = "$row[field15]";
$IKdfield16 = "$row[field16]";
$IKdfield17 = "$row[field17]";
$IKdfield18 = "$row[field18]";
$IKdfield19 = "$row[field19]";
$IKdfield20 = "$row[field20]";
$IKdfield21 = "$row[field21]";
$IKdfield22 = "$row[field22]";
$IKdfield23 = "$row[field23]";
$IKdfield24 = "$row[field24]";
$IKdfield25 = "$row[field25]";
$IKdfield26 = "$row[field26]";
$IKdfield27 = "$row[field27]";
//output results
echo "$IKfield01, $IKfield02, $IKfield03, $IKfield04, $IKfield05, $IKfield06, $IKfield07, $IKfield08, $IKfield09, $IKfield10, $IKfield11, $IKfield12";
echo "$IKfield13, $IKfield14, $IKfield15, $IKfield16, $IKfield17, $IKfield18, $IKfield19, $IKfield20, $IKfield21, $IKfield22, $IKfield23, $IKfield24";
echo "$IKfield25, $IKfield26, $IKfield27, (EOR) <br>";
$resultcounter++;
$row_count++;
}
?>

You could use WHERE 1 so that you always end with and AND at every clause.
The other solution is to create a variable $where with the criteria and check if there's any content before adding clauses, if yes, you add an AND
<?php
$sql = "SELECT * FROM table"
$where = "";
// ...
if($myparam) {
if(strlen($where) > 0) $where .= ' AND';
$where .= " myparam ='myval'";
}
// ...
if(strlen($where) > 0) $sql = $sql . ' WHERE ' . $where;

I would build an array of parameters, and implode them into a query:
$query_array = array();
$fields = array(
1=>'genus',
2=>'specificEpithet',
3=>'stateProvince',
4=>'county',
5=>'family',
6=>'locality',
7=>'OtherCatalogNumbers',
8=>'recordedBy',
9=>'recordNumber',
10=>'catalogNumber'
);
for($i = 1; $i <= 10; $i++){
$field = 'field' . str_pad($i, 2, " ", STR_PAD_LEFT);
if(!isset($_GET[$field])
continue;
$value = mysqli_real_escape_string($mysqli,$_GET[$field]);
$query_array[] = $fields[$i] . ' LIKE %' . $value . '%';
}
$query = "SELECT * FROM table WHERE " . implode(' AND ', $query_array) . " LIMIT $maxsearch";
$row_count = 0;
$result = mysql_query($query) or die("MS-Query Error in select-query");
//etc

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.

Split results into variables after mysqli query

I have following:
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
if (!isset($izbaci_zarez[0])) {
$izbaci_zarez[0] = "";
$pods0 = "";
} else {
$pods0 = $izbaci_zarez[0];
}
if (!isset($izbaci_zarez[1])) {
$izbaci_zarez[1] = "";
$pods1 = "";
} else {
$pods1 = $izbaci_zarez[1];
}
if (!isset($izbaci_zarez[2])) {
$izbaci_zarez[2] = "";
$pods2 = "";
} else {
$pods2 = $izbaci_zarez[2];
}
}
echo "1:" . $pods0;
echo "2:" . $pods1;
echo "3:" . $pods2;
echo "4:" . $pods3;
echo "5:" . $pods4;
}
Query gives me results: 30313233.
After while loop I tried to control variables $pods0, $pods1, $pods2, $pods3 and $pods4 but It gives me result for first variable only; $pods0 is 30..
Is it possible to get other values from variables?
You have some problems with your code, first of all, you do not need use isset() function, it always returns true because of the variable is exists. Secondly, if $izbaci_zarez[1] is empty you do not need to set it again with an empty value. The last thing, store the data in an array instead of a variable and it will not limit your variables count (Because of it will hard to follow) and set the values to their correct index.
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
$i = 1;
$pods = array();
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
$pods[$i] = $izbaci_zarez[0];
$i++;
}
echo "1:" . $pods[1];
echo "2:" . $pods[2];
echo "3:" . $pods[3];
echo "4:" . $pods[4];
echo "5:" . $pods[5];
// and etc...
}

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.

How to log my all updates of a page in php-mysql

In my project I have a product add page and it has an edit option.
Added product details will goto the product table in mysql database.
I want to log all the editings which includes the time and user it edits.
I done it by creating a copy of table product as product_updated.
Whenever the product is edited, the product table value of that product is stored in the product_updated table with time and user updated.
Then product table is updated with new values.
I'm done it in php mvc framework. My model has the following function.
This is worked,but it shows some error when product name contains ' symbol.
What is the correct way to do this?
function product_edit_save($id = 0,$user_id) {
$query= $this->db->query("SELECT * FROM product WHERE product_id = $id");
$result = $this->db->fetch_object($query);
foreach ($result as $row) {
$this->db->query("INSERT INTO product_updated SET product_id=$row->product_id,product_code = '$row->product_code', product_name =' $row->product_name', product_category = $row->product_category,
product_subcategory = $row->product_subcategory, product_supplier = ' $row->product_supplier', product_generic = $row->product_generic,
product_manufacturer =$row->product_manufacturer,product_image = '$row->product_image', product_combination = $row->product_combination, product_package =$row->product_package,
product_desc = '$row->product_desc', product_type = '$row->product_type', product_division = '$row->product_division',
product_chemical_name='$row->product_chemical_name',product_updatetime=now(),product_update_user=$user_id,product_banned=$row->product_banned", true);
}
$validate_form = true;
$validate_error = array();
$return['status'] = false;
$return['message'] = '';
if ($_POST) {
$code = isset($_POST['code']) ? $_POST['code'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$category = isset($_POST['category']) ? $_POST['category'] : '';
$sub_category = isset($_POST['sub_category']) ? $_POST['sub_category'] : '';
$generic = isset($_POST['generic']) ? $_POST['generic'] : '';
$manufacturer = isset($_POST['manufacturer']) ? $_POST['manufacturer'] : '';
$combination = isset($_POST['combination']) ? $_POST['combination'] : '';
$package = isset($_POST['package']) ? $_POST['package'] : '';
$desc = isset($_POST['desc']) ? $_POST['desc'] : '';
$type = isset($_POST['type']) ? $_POST['type'] : '';
$division = isset($_POST['division']) ? $_POST['division'] : '';
$chemicalname = isset($_POST['chemicalname']) ? $_POST['chemicalname'] : '';
$ban = isset($_POST['ban']) ? $_POST['ban'] : 0;
if (isset($_POST['supplier'])) {
$supplier = $_POST['supplier'];
} else {
$supplier = array();
}
if ($code == "") {
$validate_error[] = "Code";
$validate_form = false;
} else {
$esc_id = $this->db->escape($id);
$esc_code = $this->db->escape($code);
if ($this->db->num_rows($this->db->query("SELECT product_code FROM product WHERE product_code = $esc_code AND product_id != $esc_id")) != 0) {
$validate_error[] = "Code Duplication";
$validate_form = false;
}
}
if ($name == "") {
$validate_error[] = "Name";
$validate_form = false;
}
if ($category == "-1") {
$validate_error[] = "Category";
$validate_form = false;
}
if ($manufacturer == "-1") {
$validate_error[] = "Manufacturer";
$validate_form = false;
}
if ($validate_form) {
$esc_filename = $this->db->escape('');
$isimage = "";
if (isset($_FILES['image']['name'])) {
$this->library('upload');
$image = $this->library['upload']->image($_FILES['image'], UPLOAD, '180');
if ($image['status'] == 0) {
$validate_error[] = 'image ( ' . $image['message'] . ' )';
$validate_form = false;
} else {
$esc_filename = $this->db->escape($image['filename']);
$isimage = ",product_image = $esc_filename";
}
} else {
$isimage = "";
}
}
if ($validate_form) {
$esc_id = $this->db->escape($id);
$sub_category = isset($_POST['sub_category']) ? $_POST['sub_category'] : '';
$generic = isset($_POST['generic']) ? $_POST['generic'] : '';
$manufacturer = isset($_POST['manufacturer']) ? $_POST['manufacturer'] : '';
$combination = isset($_POST['combination']) ? $_POST['combination'] : '';
$package = isset($_POST['package']) ? $_POST['package'] : '';
$desc = isset($_POST['desc']) ? $_POST['desc'] : '';
$type = isset($_POST['type']) ? $_POST['type'] : '';
$division = isset($_POST['division']) ? $_POST['division'] : '';
$esc_code = $this->db->escape($code);
$esc_name = $this->db->escape(strtoupper($name));
$esc_category = $this->db->escape($category);
$esc_sub_category = $this->db->escape($sub_category);
$esc_supplier = $this->db->escape(implode(",", $supplier));
$esc_generic = $this->db->escape($generic);
$esc_manufacturer = $this->db->escape($manufacturer);
$esc_combination = $this->db->escape($combination);
$esc_package = $this->db->escape($package);
$esc_desc = $this->db->escape($desc);
$esc_type = $this->db->escape(strtoupper($type));
$esc_division = $this->db->escape(strtoupper($division));
$esc_ban=$this->db->escape(strtoupper($ban));
$esc_chemicalname = $this->db->escape($chemicalname);
try {
$this->db->transaction();
$this->db->query("UPDATE product SET product_code = $esc_code, product_name = $esc_name, product_category = $esc_category,product_chemical_name=$esc_chemicalname,
product_subcategory = $esc_sub_category, product_supplier = $esc_supplier, product_generic = $esc_generic,
product_manufacturer = $esc_manufacturer, product_combination = $esc_combination, product_package = $esc_package,
product_desc = $esc_desc $isimage,product_type = $esc_type, product_division = $esc_division,product_banned=$esc_ban WHERE product_id = $esc_id", true);
$this->db->commit();
$return['status'] = true;
$return['message'] = "Successfully Updated";
return $return;
} catch (Exception $e) {
$this->db->rollback();
$return['message'] = "Failed to Update";
return $return;
}
} else {
$return['message'] = "Invalid Field " . implode(", ", $validate_error);
return $return;
}
}
}
mysql_real_escape_string() is deprecated.
Use stripslashes() to clean the variables and (optional) use addslashes() to add them back when reading them.
Example:
$supplier = stripslashes($_POST['supplier']);
As a sidenote, do not use isset(), use !empty().
if(!empty($your_variable)) { ... }
instead of
if(isset($your_variable)) { ... }
In order to make this or you should follow the best practices when it comes to prevention from SQL Injection http://en.wikipedia.org/wiki/SQL_injection
You could either use prepared statements (best option) or at least escape the data that you input in your SQL queries using mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php
This way a query like this
SELECT * FROM table_name WHERE column_name = 'test'data';
will become this
SELECT * FROM table_name WHERE column_name = 'test\'data';
And you will stop getting errors.

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;
}

Categories