tags:

views:

61

answers:

2

I am working on an issue management system, developed in PHP/MySQL. It requires search functionality, where the user will mention the search parameters and based on these parameters the system will return the result set.

To solve this I am trying to write a function and all the user selected parameters are passed as arguments. Based on the arguments I will dynamically generate the query. At times(based on choices made by user) one or more of these arguments can be null.

A Sample Query:

    select * from
        tickets 
        inner join ticket_assigned_to 
            on tickets.id=ticket_assigned_to.ticket_id
    where 
        tickets.project_id= in ('')
        and tickets.status in ('')
        and ticket_assigned_to.user_id in ('')
        and tickets.reporter_user_id=''
        and tickets.operator_user_id in ('')
        and tickets.due_date between '' and ''
        and tickets.ts_created between '' and '';
    

I also need to handle cases where the arguments can be ORed or ANDed in the query.

For example:

 
    select * 
    from
        tickets 
        inner join ticket_assigned_to 
            on tickets.id=ticket_assigned_to.ticket_id
    where 
        tickets.project_id= in ('')
        and tickets.status in ('')
        or tickets.due_date = ''
        or tickets.ts_created between '' and '';

I am also planning to use the same function at other places in the project also. Like to display all the tickets of a user or all tickets created between given dates and so on...

How to handle this situation?
Should I go with a single function which handles all this or numerous small functions? Need guidance here.

+1  A: 

I don't think that directly converting a users serach query into mysql query is a good idea. Basically you just become more vulnerable against SQL injection.

I recommend to use an abstraction layer like PHP ActiveRecord and for search maybe a full-text search engine like Sphinx which has it's own advanced query mode, where you can query via @author Peter or Sam | Martha.

Marcel J.
Even if I remove the search feature from the picture, I still need to have answers for questions like....... 1. Show all issues assigned to me and having status = 'open' or 2. All issues in a given project created since last month assigned to me and open... and so on.. so I still need to have function(s) for these.
Varun
Sphinx would shine for full text search over MySQL, since he can specify criteria for indexed columns, MySQL fits here. Most ticket systems use an RDBMS, e.g. trac uses sqlite
Greg K
+1  A: 

What about using the Specification Pattern to build up your query criteria?

Links are not PHP specific but hopefully convey how you might approach building up your WHERE criteria:

LINQ expression trees & the Specification pattern
C# Specification Pattern Example
Google Books result - Jason Sweat's Guide to PHP Design Patterns
Learn the Specification Pattern

Greg K