Variable inside the WHERE of a select

Asked

Viewed 1,829 times

0

I have a variable that changes your content according to some user actions!

I intend to use this same variable within a select, as follows!

" Select * FROM tabele WHERE '$variável' "

But when I apply variável in the Select presents the following error:

Fatal error: Call to a member function fetchAll() on boolean

As stated above the content of this variable is dynamic, its content may be:

$variavel = "Item1 = 'Dado'";

or:

$variavel ="Item1 = 'Dado' AND Item2 = 'Dado'";

It varies according to the user’s action. However, if I add the contents of the variable in WHERE directly, it works perfectly. Ex:

" Select * FROM tabele WHERE Item1 = 'Dado' AND Item2 = 'Dado'"

My question is:

How do I apply the contents of the variable inside the select without error? Apparently it has to do with the single and double quotes, but I’ve already made some changes here and nothing has worked!

  • @Bacco the code is basically this! The only thing I did not add was the function that forms the content of the variable! But I think that the problem is not with her! Because in my tests I deactivated the function and the problem persisted! So I’m only working with the variable (which is in the question) and select (which is also in the question).

1 answer

4


Basically it’s syntax error, it doesn’t make sense:

"Select * FROM tabele WHERE '$variável'"

For when it does

$variavel ="Item1 = 'Dado' AND Item2 = 'Dado'";

Your query is in quotes

Select * FROM tabele WHERE 'Item1 = 'Dado' AND Item2 = 'Dado''

This type of error can be easily detected with a echo $sql; before sending the query. For your case, the line would be this:

"Select * FROM tabele WHERE $variável"

or more elegant, to avoid interpolation on the whole string:

'Select * FROM tabele WHERE '.$variável
  • 1

    The mistake was mine! It was really a syntax error and I didn’t see it! A WHERE was getting empty! It was something like "WHERE item = Item2 = given

Browser other questions tagged

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