0

I have 3 individual FULLTEXT indexes on columns: City, Text, Group and 3 corresponding values $city, $text and $group.

What I want to do is basically have multiple WHERE conditions that only run if the variable is defined. E.G if $city and $text are defined a WHERE for $city in column City and a WHERE for $text in column Text.

This is my current MySQL query:

$result = mysql_query("
SELECT * FROM Posts 
WHERE MATCH (City) AGAINST ('$city') 
ORDER by Date DESC LIMIT $limit_posts OFFSET $first_post
");

I don't know how to do it without messing the query.

How can I do it?

3 Answers 3

1

You could do something like this:

Warning: Hacky code ahead

// Column name => column value
$filter = array(
    'city' => $city,
    'text' => $text,
    'group' => $group,
);

$filter_sql = 'WHERE ';
foreach ($filter as $key=>$value)
    $filter[$key] = "MATCH ($key) AGAINST ('$value') ";

$filter_sql .= implode($filter, ' AND ');

$query = "SELECT * FROM Posts 
$filter_sql
ORDER by Date DESC LIMIT $limit_posts OFFSET $first_post";

Just make sure you properly populate $filter array based on what columns you want to filter on.

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

Comments

0

Probably easiest to build the query dynamically in your application code.

Comments

0

The best solution is to compose the query dynamically as indicated elsewhere. But an ugly hack where this is not possible would be:

SELECT * FROM Posts 
WHERE ('$city'='' OR MATCH (City) AGAINST ('$city'))
  AND ('$text'='' OR MATCH (text) AGAINST ('$text')) 
  AND ('$group'='' OR MATCH (group) AGAINT ('$group'))

Comments

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.