If I declare a variable in a SELECT query is it required?

Asked

Viewed 157 times

2

My problem is that I won’t always receive the variables, so I need a way that doesn’t make them mandatory even if I declare them, for example in the query below:

"SELECT * FROM clientes WHERE clientes.nome = :nome";

Var :nome is mandatory;

then I need that even if the variable :nome does not contain a value, the query returns all clients

2 answers

4

Check with IF.

if(!empty($nome)){
$where = "clientes.nome = :nome";
} else {$where = "";}

$query = "SELECT * FROM clientes WHERE $where";

You can edit the Else to add other rules to Where.

2


I recommend doing this directly to php.

You can use a if to do this, as Stéfano suggested, or in a more simplified way:

$sql = empty($nome) ? "SELECT * FROM clientes" : "SELECT * FROM clientes WHERE clientes.nome = :nome";

Browser other questions tagged

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