0

I have a variable that is a filter for my query:

$filterString.=" AND venue = ".$venue;

And I want this variable (when called) to add the AND filter statement to my query.

My query is as follows (with the failed attempt):

mysql_query("SELECT * FROM event 
WHERE city = '$city' " . $filterString . " 
ORDER BY date ASC");
6
  • Please don't do this (substitute user-suplied data directly into an SQL query). You're allowing an SQL injection attack. Instead use a "prepared statement" (data-binding of placeholders in the query). Commented Aug 31, 2013 at 3:55
  • Even if I use mysql_real_escape_string? Commented Aug 31, 2013 at 4:02
  • 1
    @David-SkyMesh ... How do you know that $city and $venue are "user-suplied data" Commented Aug 31, 2013 at 4:38
  • What is the error that you get? Commented Aug 31, 2013 at 4:40
  • Supplied argument is not a valid MySQL result resource Commented Aug 31, 2013 at 4:44

2 Answers 2

1

I think the venue needs to be surrounded by single quotes:

$filterString.=" AND venue = '".$venue.".";

However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.

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

3 Comments

You can bind an additional parameter that controls (logically) whether the AND statement has effect. e.g: ` where city = ? and ((not ?) or venue = ?))`
it would be better if you showed @pedrum how to do the parameterised query, as well as the logical inclusion/exclusion of the filter.
Is there any way to have a WHERE something = Anything?
0

You could use:

$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';

Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.

To answer your other comment question:

WHERE 1

is a valid condition that works like Anything

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.