My advice: I probably wouldn't bother to do this. Apart from the specific problems others have pointed out (SQL injection, forgot to return), there's a bigger issue I have with this: you're assuming that all queries will fit nicely into this form. Limitations of your function include:
- No support for joining multiple tables.
- No support for inner selects.
- You always select all columns using
*
- a bad idea in general. You have no support for selecting only some columns.
- No support for
GROUP BY
.
- When you want all rows you still have to pass a where clause like '1=1'.
- etc...
Now you could extend your function to allow for these other possibilities, but it will become more complex and you'll just end up with a custom language for creating SQL queries but doesn't resemble SQL. Sometimes it is a good idea to create a custom language for accessing an SQL database but most often it is just a waste of your time and will make it hard for others to understand your code. Stick to using standard libraries and standard interfaces where possible. If you want to avoid using SQL you could investigate using an Object-Relational Mapping (ORM) instead.
If you want to keep SQL out of your code, try to make an interface that actually does something specific to your application (getFriends, getPostsByUser) instead of something that is too generic.