Answer the question
In order to leave comments, you need to log in
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
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
Answer the question
In order to leave comments, you need to log in
you need to test, by time, by resources, and then decide what is best for you
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`');
If the code is executed synchronously and in one thread, then there is no point in blocking a new connection.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question