PHP/MySQL - Multiple queries at the same time

后端 未结 3 791
抹茶落季
抹茶落季 2021-01-28 15:10

I have 24 databases with a table labeled email_queue.

I have another database with a list of all the databases that have the email_queue table

3条回答
  •  后悔当初
    2021-01-28 15:32

    I think having this many databases is probably a sign of bad design. If you can't change it and need to move forward now, I suggest one of two options:

    1. Run the same script with a parameter to select which database to use. You should be able to find resources on how to do this
    2. Use non-blocking queries; the rest of this answer will be spent talking about this.

    Here's a somewhat complete example using the mysqli extension (requires the mysqlnd driver):

    $credentials = array(
        array(
            'host' => 'host1',
            'user' => 'user',
            'password' => 'password',
            'database' => 'database'
        ),
        array(
            'host' => 'host2',
            'user' => 'user',
            'password' => 'password',
            'database' => 'database'
        ),
        // credentials for other sites
    );
    $dbcs = array();
    foreach ($credentials as $config) {
        $dbcs[] = array($db = new mysqli(
            $config['host'],
            $config['user'],
            $config['pass'],
            $config['database']
        ));
        $query = ""; // here is your query to do whatever it is with your table
        $db->query($query, MYSQLI_ASYNC);
    }
    
    $results = array();
    $errors = array();
    $rejected = array();
    $secondsToWait = 1;
    
    while (!empty($dbcs)) {
        foreach ($dbcs as $key => $c) {
            $db = $c[0];
            if (mysqli_poll($c, $errors, $rejected, $secondsToWait) == 1) {
                $r = $db->reap_async_query();
    
                // here you would do your fetches for each query, such as
                $results[] = $r->fetch_assoc();
    
                // do what you need to do with the result
    
                // then cleanup
                $r->free();
                $db->close();
                unset($dbcs[$key]);
            }
        }
    }
    

    Note that it does have drawbacks, such as a failed query may bring down the whole program.

提交回复
热议问题