Possibility to search in one or more columns of the same SQL table

Asked

Viewed 43 times

-4

I have a splint where several products are displayed. On the left side, there are several options for the person to make filters in the product list.

I am trying to create a form if the variable has value, it will be mounted in parts.

This is my code:

if (!empty($_GET) && (!empty($_GET['search']))) {
    $where = "WHERE"; 
}else{
    $url_atual = "";
}

if (isset($_GET['search']) && ($_GET['search'] != "")) {
    $serch = "titulo LIKE '%".$_GET['search']."%' ";
}else{
    $serch = "";
}

if (isset($_GET['cat']) && ($_GET['cat'] != "")) {
    $cat = "AND categoria = ".$_GET['cat']." ";
}else{
    $cat = "";
}

if (isset($_GET['cat_sub']) && ($_GET['cat_sub'] != "")) {
    $cat_sub = "AND subcategoria IN ('".$_GET['cat_sub']."')";
}else{
    $cat_sub = "";
}

if (isset($_GET['fpag']) && ($_GET['fpag'] != "all")) {
    $fpag = "AND fixoHora = '".$_GET['fpag']."' ";
}else{
    $fpag = "";
}


$projetos = $conn->query("SELECT * FROM projetos {$where} {$serch} {$cat} {$cat_sub} {$fpag} LIMIT {$inicio},{$itens_por_pagina}");

Problem

As I am wearing AND, at the beginning of the variables, if some variable is not initialized, such as search, of error, because it would start like this:

SELECT * FROM projetos AND cat = 1

There is a better way to do this research?

Thanks for the help!

2 answers

-1

simple, before checking when you set the WHERE, put WHERE 1=1 ai ALL variables you use the AND, i.e., if any value does not exist, it will use WHERE 1=1 (always true and runs SQL), if any condition comes it will always be started with AND, then the final output is WHERE 1=1 AND C1=v1

  • I did it that way, it worked.

-1

Try Something like:

if (!empty($_GET) && (!empty($_GET['search']))) {
    $where = "WHERE"; 
$projetos = $conn->query("SELECT * FROM projetos {$where} LIMIT {$inicio},{$itens_por_pagina}");

}else if (isset($_GET['search']) && ($_GET['search'] != "")) {
    $serch = "titulo LIKE '%".$_GET['search']."%' ";
$projetos = $conn->query("SELECT * FROM projetos {$serch}  LIMIT {$inicio},{$itens_por_pagina}");

}else if (isset($_GET['cat']) && ($_GET['cat'] != "")) {
    $cat = "AND categoria = ".$_GET['cat']." ";
$projetos = $conn->query("SELECT * FROM projetos {$cat}  LIMIT {$inicio},{$itens_por_pagina}")

}else if (isset($_GET['cat_sub']) && ($_GET['cat_sub'] != "")) {
    $cat_sub = "AND subcategoria IN ('".$_GET['cat_sub']."')";
}else if (isset($_GET['fpag']) && ($_GET['fpag'] != "all")) {
    $fpag = "AND fixoHora = '".$_GET['fpag']."' ";
$projetos = $conn->query("SELECT * FROM projetos {$fpag} LIMIT {$inicio},{$itens_por_pagina}"); 

}
  • No da, because already in the second condition would be wrong. by not having the WHERE,

  • as ta your table in the database?

  • I don’t understand the meaning of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.