I am trying to build a dynamic query using PHP and MySQL.
What I have done is created a table (ie. field_relations
)
This field has 5 column
- field_name (the name of a field "ie. account_id, account_name....")
- display_label (The way how the field should be displaced to the use "ie. Account Id, Name")
- table_name (the table where this field belong to "ie. accounts")
- related_to (the field relation to a different table "if any." The default value is
NULL
) - related_to_field (the field where it points to "if any." The default value is
NULL
)
Here is a sample data
field_name display_label table_name related_to related_to_field
account_id Account ID accounts NULL NULL
account_name Name accounts NULL NULL
first_name First Name contacts NULL NULL
last_name Last Name contacts NULL NULL
contact_id Contact ID contacts NULL NULL
account_id Account ID contacts accounts account_id
task_id Task ID tasks NULL NULL
subject Subject tasks NULL NULL
owner_id Assigned To contacts contacts contact_id
daily_sales Sales transactions accounts account_id
sold_on Sold On transactions NULL NULL
So if I create a HTML form with 3 seconds
- Pick column to display
- Add formula to columns (optional)
- Pick Condition clause (optional)
- "Display Results" button.
The first part of ths form will display all values that are list in the display_label
column.
If a user picked Name, First Name, Last Name
Then the query will need to look like this
SELECT accounts.account_name, contacts.first_name, contacts.last_name
FROM accounts
INNER JOIN contacts ON contacts.account_id = accounts.account_id
after the query is done it will be executed.
Or, if the user selected "Name, Sales." Then the user want to apply SUM function on column daily_sales
. And finally the user selected a filter for Sold On between '2014-01-01 00:00:00' AND '2014-10-01 00:00:00'
Then the query will need to look like this
SELECT accounts.account_name, SUM(daily_sales) AS daily_sales
FROM accounts
LEFT JOIN sales ON sales.account_id = accounts.account_id
WHERE sales.sold_on BETWEEN '2014-01-01 00:00:00' AND '2014-10-01 00:00:00'
GROUP BY accounts.account_name
after the query is done it will be executed.
How can I generate such a query? do I need to add more column to the field_relations
table?
I am not worried on how to build the PHP form to capture the user specs but I am trying to figure out how to generate they MySQL query correctly?
Thank you in advance for your help and time.