简体   繁体   中英

What's the best way to apply the same rule in multiple queries?

My application has a dashboard screen which has many charts showing metrics and results of user activity, sales performance, etc.

These results can be filtered by date, user and many other options. Supposing I've got one query for each chart, what's the best way to apply the same filtering rule in these multiple queries? Whats the best way to replicate the same "where" clause (the same filtering rule) accross many queries?

As example,

SELECT * FROM users WHERE date = '2014-10-03';

SELECT * FROM products WHERE date = '2014-10-03';

Both queries have same rules. Some suggested to set a variable with this rule and concatenate it to other queries. Something like:

$where = "WHERE date = '2014-10-03'";

$query = "SELECT * FROM users ". $where;

...

$query = "SELECT * FROM products ". $where;

...

But I can't see this as a good pratice.

If it is similar to issue I had in past I guess you need these restricted by many often repetitive WHERE conditions. User, department permission, time, etc.

What worked in my case was making these into string variables and reusing them across queries that produce charts and graphs. Of course, do not insert user data into your dynamic queries. Hope it helps.

Would it not be a better idea to only keep the value dynamic in case tables do not share the same column name for date.

$date = '2014-10-03';

$query = "SELECT * FROM users WHERE `date_added` = $date";

$query = "SELECT * FROM products WHERE `date_purchased` = $date";

Note: use appropriate validation and security checks for using user input data in sql.

I think you should look into using Prepared Statements. Similar to bind variables in Oracle.

The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters

Good explanation here: http://docs.php.net/pdo.prepared-statements

Prevents SQL injection attacks as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM