Reputation: 45
I have a variable in PHP. I want to check my PHP variable in MySQL query and if it is not null use it in a where clause.
select * from T1
where post = "news" and $city = cityname and $city is not null
$city
is PHP variable.
I have a problem when $city
is null, that should show all news posts but it returns nothing.
Upvotes: 0
Views: 90
Reputation: 147146
Since $city
is a PHP variable, if it is NULL
then when you echo it in your query you will simply get nothing. That will make an invalid query; it will look like this:
select * from T1
where post = "news" and = cityname and is not null
To make this work, you need to enclose $city
in your query in quotes, and then rather than comparing it to NULL
, compare it to the empty string i.e.
select * from T1
where post = "news" and ('$city' = cityname or '$city' = '')
Note that the correct logical operator is or
for this use case.
As was pointed out in the comments, you should look into prepared statements. This question has some really useful information: How can I prevent SQL injection in PHP?
Upvotes: 3
Reputation: 9
Try this
select * from T1
where post = "news" and ($city = cityname or $city is not null )
Upvotes: -1