Search code examples
phpmysqlimulti-query

Mysqli Multi Query - Sort Results


i want to save every result from an sql statement in a differen array. I tried:

        $sql = "SELECT * FROM `link_server` WHERE `in_use` = false;";
        $sql .= "SELECT * FROM `link_queue` WHERE `active` = false;";

        if ($db->multi_query($sql))
        {
            do
            {
                // Erstes Abfrageergebnis ausgeben
                if ($result = $db->store_result())
                {
                    // Abfrageergebnis ausgeben
                    while ($server_fetch = $result->fetch_array())
                    {
                        $server[] = $server_fetch;
                    }

                    $result->close();

                }
                // Trenner fuer Zweites Abfrageergebnis
                if ($db->more_results())
                {
                    echo "<hr />test";
                    $queue[] = $server_fetch;
                }
            } while ($db->next_result());
        echo "Servers:";
        print_r($server);
        echo "Queue:";
        print_r($queue);
        }           

The result from the first statement should be saved in the array $server, and the second should be saved in the array $queue.

The above example stores the complete return (from both statements) in the first array ($server). The second array is empty.

How can i solve that?

Thanks for your help!


Solution

  • $db->more_results() is a way of flagging that the end of the results of a query have been reached, not to get the next set of results. You can use it to tell your loop to start loading the next array - for example by setting a flag.

    if ($result = $mysqli->store_result()) {
        while ($server_fetch = $result->fetch_row()) {
            if (!$second) {
                $server[] = $server_fetch;
            } else {
                $queue[] = $server_fetch;
            }
        }
        $result->close();
    }
    /* next set of results */
    if ($mysqli->more_results()) {
        $second = true;
    }
    

    Alternatively, you could use a variable variable like so:

    /* set up variables  */
    $server = array();
    $queue = array();
    $active = 'server';
    
    /* execute multi query */
    if ($mysqli->multi_query($query)) {
        do {
            /* store result set */
            if ($result = $mysqli->store_result()) {
                while ($server_fetch = $result->fetch_row()) {
                    ${$active}[] = $server_fetch;
                }
                $result->close();
            }
            /* next set of results */
            if ($mysqli->more_results()) {
                $active = 'queue';
            }
        } while ($mysqli->next_result());
    } 
    

    Although I have to concur with the commentors, this adds a lot of effort and additional code complexity to an otherwise simple pair of requests.