I am trying to create a sort of dynamic function that will return a formatted string that will be added to an SQL query. The function will take an array of data, and based on the data, it will format it into a string that will be added to the SQL query, the string will include the WHERE
, ORDER BY
, and LIMIT
of the query.
At the moment i have a working set of if statements, which takes the data in the array and creates the string. This is the output:
WHERE status != 2 AND category_id = 3 ORDER BY views ASC , date DESC
That's how its supposed to show in the end (i didn't add the limit
), but i want to create a function that will do it all dynamically instead of all of the if statements for each array type.
At the moment, i am working with an array like this:
Array
(
[where] => Array
(
[status] => Array
(
[op] => !=
[value] => 2
)
[category_id] => Array
(
[op] => =
[value] => 3
)
)
[orderBy] => Array
(
[views] => ASC
[date] => DESC
)
[offsetLimit] => Array
(
[offset] =>
[limit] =>
[full] => LIMIT 0, 12
)
)
The way it is structured right now is:
where
is an array that holds the options in it, so status
and category_id
are the items i want to appear as WHERE status
.. etc.
In each there is an op
, this is the operation to perform, and after that is the value, so it would end up as Where status != 2
.
orderBy
just outputs the key and the value, e.g. views ASC
.
offsetLimit
allows you to either send the offset and limit separate and the function will put it together in the output, or you can send the string of it already in the full
setting.
I'm sure its possible to create a function that will handle this and be dynamic to support more options, i just cant get my head around it for some reason at the moment.
Thanks!
EDIT: To be clear, i do not want to get any data from the database with the function, the functions only purpose is to format the data given to it. The array sent to the function will have the table names and everything the function needs in order to FORMAT the string.