0

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.

this is my table: enter image description here

17
  • $city is a column name ? Commented Nov 28, 2018 at 10:52
  • 5
    You should not even need the $city IS NOT NULL check, AFAIK. By the way, you should read about how to use prepared statements in PHP. Commented Nov 28, 2018 at 10:53
  • Possible duplicate of Use a $variable inside a SQL string? Commented Nov 28, 2018 at 10:55
  • 2
    So you have column with name "7" ? Commented Nov 28, 2018 at 11:08
  • 1
    If you get this value from a form ($_POST['city']), then most likely it is never NULL to begin with, but rather an empty string. Commented Nov 28, 2018 at 11:43

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

Comments

-1

Try this

select * from T1
where post = "news" and  ($city = cityname or $city is not null )

2 Comments

please mention description
Can you explain how that solves the problem? There is no colum named $city

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.