[Tutorial] How to order results from multiple tables. - WulfGamesYT/MultiDatabasePDO GitHub Wiki

Say if you have a competition with tables in your databases called "Competition" and each row has a team and their score, and you want to display a leaderboard on your website to show the top 10 teams with the most score, all you need to do is the following:

How it works:

  1. You query all tables to find the top 10 scores in each table.
  2. You get all the top 10 scores from each table stored all together.
  3. You sort the results by the "Score" column in descending order using MultiDatabasePDO.

Example with code:

//Include MultiDatabasePDO and connect to each database.
require "./MultiDatabasePDO/MultiDatabasePDO.php";
$multiPDO = new \WulfGamesYT\MultiDatabasePDO\MultiDatabasePDO([
    ["mysql", "1.1.1.1", "database_1", "username", "password"],
    ["mysql", "2.2.2.2", "database_2", "username", "password"]
]);

//Check if there were any errors connecting.
if($multiPDO->hasAnyErrors()) {
    error_log("Error connecting to database(s): " . $multiPDO->getFailedConnections());
    exit("Error connecting to our main databases! Please try again later.");
}

//Order the teams by score, limit 10.
$displayLimit = 10;

$winningTeams = $multiPDO->prepare("SELECT * FROM Competition ORDER BY Score DESC LIMIT $displayLimit");
$winningTeams->execute();
$winningTeams->sortBy("Score", "DESC");
$winningTeams->limitTo($displayLimit);

while($team = $winningTeams->getNextRow()) {
    echo $team["Score"] . " | " . $team["TeamName"] . PHP_EOL;
}

//Close all database connections.
$multiPDO->finishAndClose();

You will then get something like the following printed on your page:

75 | Team 17
71 | Team 21
70 | Team 8
70 | Team 4
63 | Team 1
61 | Team 5
60 | Team 3
56 | Team 10
54 | Team 9
50 | Team 15