Merge AND Order multiple MySQL Results in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Merge AND Order multiple MySQL Results in PHP

Post by IGGt »

Is it possible to take the result from 4 different MySQL connections (assuming the query and the tables were the same for all 4), and then merge the results, AND sort the result before presenting it (without writing it back into the database, sorting it, and then exporting it again).

$query = "SELECT `Date`, `Result` FROM tablename;";

connect to Database 1 and run query => query1[]
connect to Database 2 and run query => query2[]
connect to Database 3 and run query => query3[]
connect to Database 4 and run query => query4[]

$full = array_merge(query1,query2,query3,query4);

then Print the result into a table, but Ordering it by the `Date` element.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Merge AND Order multiple MySQL Results in PHP

Post by requinix »

Sure. Dump all the results into one array and usort it. Or if you want to do it smarter, use an insertion sort as you're adding.
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: Merge AND Order multiple MySQL Results in PHP

Post by mikosiko »

.. or you can query your 4 DB's with a single query and apply your ORDER BY directly in that query... no further actions needed in PHP (array_merge or usort)

Edit: Assuming your DB's are in the same server
Post Reply