A
A
Anton B2015-11-25 14:17:15
PHP
Anton B, 2015-11-25 14:17:15

Which is better multiple mysqli_connect() or multiple mysqli_select_db()?

Hello!
I want to reduce the number of queries to the database. But I'm afraid that setting up multiple connections is more resource intensive than selecting a database. What do you think about this, which way is better?
First way

class db {

    private $link;

    function __construct() {

        $this->link = mysqli_connect('1.1.1.1', 'user', 'pass');
    }

    function query($sql, $db) {

        mysqli_select_db($this->link, $db);

        return mysqli_query($this->link, $sql);
    }
}

$db = new db();

for ($i = 0; $i < 100; $i++) {
    $db->query('SELECT * FROM `table`', 'databaseA');
    $db->query('SELECT * FROM `table`', 'databaseB');
    $db->query('SELECT * FROM `table`', 'databaseC');
}

//connections - 1
//queries - 2 x 3 x 100 = 600

Second way
class db {

    private $links;

    function query($sql, $db) {

        if ( ! isset($this->links[$db]))
            $this->links[$db] = mysqli_connect('1.1.1.1', 'user', 'pass', $db);

        return mysqli_query($this->links[$db], $sql);
    }
}

$db = new db();

for ($i = 0; $i < 100; $i++) {
    $db->query('SELECT * FROM `table`', 'databaseA');
    $db->query('SELECT * FROM `table`', 'databaseB');
    $db->query('SELECT * FROM `table`', 'databaseC');
}

//connections - 3
//queries - 1 x 3 x 100 = 300

Thank you!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Zelensky, 2015-11-25
@SergeyZelensky-Rostov

you need to test, by time, by resources, and then decide what is best for you

A
Andrey Mokhov, 2015-11-25
@mokhovcom

surprising of course is that you have to work with several DBs at once ...
why not use it easier?
$db->query('SELECT * FROM `databaseA`.`table`');

A
Alexander Kubintsev, 2015-11-25
@akubintsev

If the code is executed synchronously and in one thread, then there is no point in blocking a new connection.

R
repeat, 2015-11-25
@repeat

Here write that change of a DB faster. You have to either believe it or use whatever you like best.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question