0
The filter may occur in the following scenarios:
- Without any
input
filled - 1 (a)
input
filled - Combinations of
inputs
, including all
SQL to be optimized:
$cnpj = isset($_GET['cnpj']) ? $_GET['cnpj'] : $_POST['cnpj'];
$razao_social = isset($_GET['razao']) ? $_GET['razao'] : $_POST['razao'];
$cod = isset($_GET['cod']) ? $_GET['cod'] : $_POST['cod'];
$dt_inicial = isset($_GET['dt_inicial']) ? $_GET['dt_inicial'] :$_POST['dt-inicial'];
$dt_final = isset($_GET['dt_final']) ? $_GET['dt_final'] : $_POST['dt-final'];
if ($cnpj != '' && $razao_social != '' && $cod != '' && $dt_inicial != '' && $dt_final != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj" AND (razao_social LIKE "%$razao_social%") AND id="$cod" AND data>="$dt_inicial" AND data<="$dt_final"';
} else {
if ($cnpj != '' && $razao_social != '' && $cod != '' && $dt_inicial != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj" AND (razao_social LIKE "%$razao_social%") AND id="$cod" AND data>="$dt_inicial"';
} else {
if ($cnpj != '' && $razao_social != '' && $cod != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj" AND (razao_social LIKE "%$razao_social%") AND id="$cod"';
} else {
if ($cnpj != '' && $razao_social != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj" AND (razao_social LIKE "%$razao_social%"';
} else {
if ($cnpj != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj"';
} else {
if ($cnpj != '' || $razao_social != '' || $cod != '' || $dt_inicial != '' || $dt_final != '') {
$sql = 'SELECT * FROM nfe WHERE cnpj="$cnpj" OR (razao_social LIKE "%$razao_social%") OR id="$cod" OR data>="$dt_inicial" OR data<="$dt_final"';
} else {
$sql = 'SELECT * FROM produtos';
}
}
}
}
}
}
try {
$query = $conecta->prepare($sql);
$query->execute();
$resultado = $query->fetchAll(PDO::FETCH_ASSOC);
}catch (PDOexception $erro) {
echo 'Erro ao selecionar: '.$erro->getMessage();
}
No doubt about the way this query of yours will make it very difficult to maintain the code and it doesn’t have to be this complex.
– gato
Because they were negative on the question?
– jlHertel
One thing I recommend is creating pagination using
LIMIT ...,...
, this because if it returns many results this will "lock". I think this answer should help http://answall.com/a/94890/3635– Guilherme Nascimento