Please house i want to create a function that will query the database to get some sets of values, this means the function have to query the database on each execution and mostly the function will be called inside a loop. now i am thinking of pulling out all the details from the database into a php array and then loop through that array to find values in the loop instead of hitting the database as many times the loop can take
Now please i need to know if mysql query will be better and faster to use or is using array faster and better?
I don’t honestly know, but I would imagine the array would be faster.
But the problem with the array is: how often with the data set be updated?
When using the database and the same query is being made in a loop, you can make it more efficient by using prepared statements. Prepare the query only once before the loop, then execute within the loop.
Eg:-
$sql = $db->prepare("SELECT * FROM table WHERE id = ?");
foreach($list as $id){
$sql->execute([$id]);
// Fetch Etc...
}
Oh I would definitely query ONE time and put all details in an array with the product id as the primary array key. If the array is built near the top of the page before output, it can be used in many ways such as form/order processing( i.e. comparing form values to this array or grabbing needed product details that are not sent with a form input.) , showing different product views from complete details to a lists of products or quick view popups. All from one array. Just my 2 cents…
really, i think using one query, output to an array and then loop through the array in body.
$outputtedarray = results from database
then the below foreach loop will only use that outputtted array more like the database is now brought out and placed above the function.
so only query happens once.
while the looping function plays with the returned array. as many times as it wants without querying the database more than twice.
Remember to build the array placing the ID as the key, so any product popup, product detail view can simply use the ID with the array to grab details of that product. Example:
This can be done directly by fetchAll using the PDO::FETCH_UNIQUE mode.
$productlist = $query->fetch(PDO::FETCH_UNIQUE);
Assuming the ID is the first column in the table, it will be the array key for its row.
If not, you can explicitly set the order of the columns in the query, where the first mentioned becomes the key, though it must be a unique column.
SELECT id, name, price FROM table
I highly recommend exploring the various PDO fetch modes, there are lots of handy tricks like this that can save you work in PHP processing.
A nice reference: https://phpdelusions.net/pdo/fetch_modes
wow thats great, i never knew of this was busy using some complex query method like distinct and all that when i can simply use a fetch module. Thanks alot