John Davidson

Reorder mysql results via php to prevent multiple queries

0 comments
Message:


I query some data from mysql database and ordering by specific key. For example: ORDER BY param1 ASC


Now I output the data via while and mysql object. And I need to do two other queries which are the same but with different order. For example: ORDER BY param2 ASC and ORDER BY param3 ASC.


I know I could save data in multidimensional array and reorder by usort. But is there any more elegant way? For example reusing the mysql object and converting directly?


Thanks for any tips or ways to make it more simple.



My Answer:
One way to achieve this without making multiple queries is to fetch all the data from the initial query and then use PHP to reorder the results based on different parameters. Here's an example:

php
// Initial query
$query = "SELECT * FROM table ORDER BY param1 ASC";
$result = $mysqli->query($query);

// Fetch all data
$data = $result->fetch_all(MYSQLI_ASSOC);

// Reorder data based on param2
usort($data, function($a, $b) {
return $a['param2'] <=> $b['param2'];
});

// Output data
foreach ($data as $row) {
// Output row
}

// Reorder data based on param3
usort($data, function($a, $b) {
return $a['param3'] <=> $b['param3'];
});

// Output data
foreach ($data as $row) {
// Output row
}


This way, you only need to make one query to fetch the data and then use PHP to reorder the results based on different parameters. This can be more efficient than making multiple queries to the database.

Rate this post

3 of 5 based on 3142 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us