Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute more or complicated SQL queries, or use PHP to filter data?

I'm building a PHP app which will get a lot of traffic. I have always learned that I should limit the number of SQL queries (right now it's about 15 per visitor). I could limit this to about half, using PHP to filter and sort data, but would this be faster? Alternatively, I could use "JOIN" in the query to reduce the number of queries, but is this really faster than executing multiple queries? Thanks!

like image 841
Rik de Vos Avatar asked Jun 21 '13 13:06

Rik de Vos


People also ask

Which is the correct function to execute the SQL queries in PHP?

The query() / mysqli_query() function performs a query against a database.

Why is SQL better for complex queries?

For complex analytical queries, SQL is unquestionably the best tool. It is easy to create queries, and even easier to tune and optimize them in order to accelerate results, shrink intermediate tables and reduce query costs.

How do I filter in PHP?

PHP filter_var() Function The filter_var() function both validate and sanitize data. The filter_var() function filters a single variable with a specified filter. It takes two pieces of data: The variable you want to check.


1 Answers

If you have 15 queries per visitor, you most likely did something wrong, unless your application is pretty big.

Using PHP to sort and filter data instead of MySQL

Doing the sorting and filtering in PHP will not make your application faster, it will make it slower for sure, MySQL is optimized to be very fast given the right indexes, so you should certainly use it when you can.

Learn about database indexing and it will make your life easier and increase your application's performance. Here is a link :

http://www.mysqltutorial.org/mysql-create-drop-index.aspx

Joining versus multiple queries

You ask if using join's would be faster than executing multiple queries.

The answer is yes, it will always be faster to use join's given the right indexes. Which also comes back to the first topic, indexing.

However, keep in mind that joining is as efficient as you make it to be, it will be extremely efficient if done right, and extremely slow if done wrong, so you must know the basics to do it right.

You can look here for an introduction to join's :

http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/

like image 157
Dany Caissy Avatar answered Sep 19 '22 22:09

Dany Caissy