I’ve a table with more than 5000 rows. Each row has a category, and I want to use these rows in my program. The problem is do I analyze these rows each time inside classes ? Or get only the class need each time, and make each class decide which data to use. I know my explanation is a mess, but look at these to examples.
PEOPLE
--
ID NAME CAT AGE
------------------------------------
1 Brad 5 23
2 Goy 3 19
2 Romeo 5 34
2 Deborah 5 40
.. .. ..
5000 Bob 1 56
now I want only to analayze the rows with cat = 5 and each row will be an object.
First Solution
SELECT * FROM people Where CAT = 5
and then in php make each class analyze the all data ?
foreach($people as $p)
{
if($p['age'] == 20)
do......
}
Second solution
in each class put a function to get the data
function get_data
{
$query = 'SELECT * FROM people WHERE cat = 5 AND age = '.$this->age.'';
then do....
}
I HAVE A LOT OF ROWS 5000 it’s an example, please help me and give me the more efficent solution
the first one will hit the databse once but the same array will loop in each class (not good)
the second will hit the database many times but will bring the indeed needed data.
With no details given, the answer is certainly to filter data with the SQL query for many reasons. There are some situations though when db-level processing is not possible (e.g. when more complicated business logic is involved) but generally you should always try to filter data before it gets into your high-level code.
That’s precisely the job databases were invented for.
In your example, collect all your ages in an array first and then run the following query:
If you’re using MySQL, the allowed size of IN sets is huge (32 Mb by default) which should be enough.