php db类与mysqli,它支持多个连接 [英] php db class with mysqli, which support multiple connections
问题描述
事情是,我需要写一个db类与mysqli和它应该支持多个连接到不同的数据库。
我知道多个连接是坏的,但我没有任何其他选择。
如果有任何好的示例类支持多个连接?
你知道当我开始写课文时我应该考虑的任何提示吗?
提前感谢,
首先想到的是一个容器类,它在其中存储MySQLi对象。
这样的东西:
class MySQLiContainer extends SplObjectStorage {
public function newConnection($ host = null, $ username = null,$ passwd = null,$ dbname = null,$ port = null,$ socket = null){
$ mysqli = new mysqli($ host,$ username,$ passwd,$ dbname,$ port ,$ socket);
$ this-> attach($ mysqli);
return $ mysqli;
}
}
//使用
$ mysqliContainer = new MySQLiContainer();
$ c1 = $ mysqliContainer-> newConnection('localhost','root','root','localDatabase');
$ c1-> query('SELECT ....');
$ c2 = $ mysqliContainer-> newConnection('mysql.remotehost.net','hackermom','bobbytables','schoolDatabase');
$ name ='Robert \'); DROP TABLE学生; - ';
$ c2-> multi_query(SELECT * FROM students WHERE name ='$ name');
如果不了解所需的功能,很难说这是一个好主意, / p>
有关 SplObjectStorage class。
The thing is that I need to write a db class with mysqli and it should support multiple connections to different databases. I know that multiple connections is bad, but I don't have any other choice.
If there is any good example of class which supports multiple connections?
Do you know any tips that I should take into consideration when I will start writing the class? What is the best practice in my case?
Thanks in advance,
First thing that comes to mind, is a container class, that stores MySQLi object in it. Something like this:
class MySQLiContainer extends SplObjectStorage{
public function newConnection($host = null, $username = null, $passwd = null, $dbname = null, $port = null, $socket = null) {
$mysqli = new mysqli($host, $username, $passwd, $dbname, $port, $socket);
$this->attach($mysqli);
return $mysqli;
}
}
//usage
$mysqliContainer = new MySQLiContainer();
$c1 = $mysqliContainer->newConnection('localhost','root','root','localDatabase');
$c1->query('SELECT ....');
$c2 = $mysqliContainer->newConnection('mysql.remotehost.net','hackermom','bobbytables','schoolDatabase');
$name = 'Robert\'); DROP TABLE students;--';
$c2->multi_query("SELECT * FROM students WHERE name = '$name'");
Without knowing more about functionality required, it's hard to say if this is a good idea though ;)
More info about SplObjectStorage class.
这篇关于php db类与mysqli,它支持多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!