How to form a request correctly

Codes here !

Moderators: egami, macek, gesf

Post Reply
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 8
Joined: Thu Dec 17, 2020 12:31 am

Thu Dec 17, 2020 12:40 am

Image

How to correctly form a query to the database in order to get the result at the output:

Game: 1 (game_id)
Партия: 1 (party_id)
User 1: 43
User 2: 11
User 3: 87

Party 2 (party_id)
User 1: 34
User 2: 43
User 3: 65

Game 2 (game_id)
Party 1 (party_id)
User 1: 90
User 2: 21
User 3: 66
simonbrahan
php-forum Fan User
php-forum Fan User
Posts: 90
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Thu Dec 17, 2020 1:48 am

SQL works in two dimensional data sets; you can't get the "game > party > user list" tree you want directly. You can do this by getting all the results from your table, then building the tree in PHP:

Code: Select all

$db = new PDO(
    'mysql:dbname=test',
    'root',
    'root',
    [
        PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
    ]
);

$res = $db->query('SELECT game_id, party_id, user_id, point FROM results ORDER BY game_id, party_id');

$results = [];

foreach ($res as $row) {
    if (!isset($results[$row->game_id])) {
        $results[$row->game_id] = [
            'game' => $row->game_id,
            'parties' => []
        ];
    }

    if (!isset($results[$row->game_id]['parties'][$row->party_id])) {
        $results[$row->game_id]['parties'][$row->party_id] = [
            'party' => $row->party_id,
            'users' => []
        ];
    }

    $results[$row->game_id]['parties'][$row->party_id]['users'][$row->user_id] = [
        'user' => $row->user_id,
        'point' => $row->point
    ];
}
Once you have your data structure, you can loop through it to print out your results:

Code: Select all

foreach ($results as $game) {
    echo 'Game: ' . $game['game'], PHP_EOL;

    foreach ($game['parties'] as $party) {
        echo 'Party: ' . $party['party'], PHP_EOL;

        foreach ($party['users'] as $user) {
            echo 'User ' . $user['user'] . ': ' . $user['point'], PHP_EOL;
        }

        echo PHP_EOL;
    }
}
This looks complicated, but most of the gnarliness is in the setting up of the tree structure.
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 8
Joined: Thu Dec 17, 2020 12:31 am

Thu Dec 17, 2020 3:17 am

Everyone is working. Thank you very much.
Post Reply