I have a table with highschools in different cities. I want to give the user the option to choose a certain city and view the schools there, or view all schools. This is my original query:

SELECT * FROM highschools
WHERE city = '$givenCity'

I need to compare 'city' to '$givenCity' only if '$givenCity' has any value.
The closest i have come to solving my problem is writing :

Where city = '$givenCity' AND '$givenCity' != 'NULL'

When I read this now, it seems so wrong...
Do you know how can I do this? And can it be done in one query?

If you aren't filtering the query at the PHP end based on $givenCity then I might try something like:
SELECT * FROM highschools WHERE city like '%$givenCity%';
That will select all matches like the given city (including matches that included the given city as a substring (I'm not sure if that will actually be a problem) or any strings that include an empty string as a substring - which is all of them.
So you feed in $givenCity as either a city or ''.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.