使 mysql 连接静态是个好主意吗?
我正在开发一个中型(可能)PHP 系统,该系统在不同的文件中随处打开 MySQL 连接,并将其制成全局变量,以便稍后包含的脚本可以访问。由于我正在创建另一个模块,因此我想避免全局变量并为每个页面请求保留相同的 mysql 连接。我当前的解决方案是这样的:
Class Db {
static public $dbConnectionArray = array();
}
对于每个请求,连接将保存在静态数组中,并在以后引用。您认为可能会出现什么问题?为什么?
我想听听一些关于如何最好地解决这个问题的意见,因为我希望减少每个脚本运行打开的连接数量(目前,一个页面请求调用了大约 6-15 个 mysql 连接到至少 3 个不同的数据库)。
I'm working on a medium-sized (probably) PHP system which had MySQL connections being opened everywhere throughout different files and, made into global variables for the later included scripts to have access to. Since I'm creating another module, I'd like to avoid globals and keeping the same mysql connection for each page request. My current solution is this:
Class Db {
static public $dbConnectionArray = array();
}
For every request, the connections would be saved in the static array and referred back to at a later time. What do you think could go wrong? And why?
Would like to hear some opinions on how to best tackle this as I would love to reduce the number of opened connections per script run (currently, one page request invoked about 6-15 mysql connections to at least 3 different databases).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无需重新发明轮子。您可以使用 mysql 持久连接来保持连接处于活动状态。 (http://php.net/manual/en/function.mysql-pconnect.php)
数据库名称和凭据相同)
通过使用持久连接,您的 PHP 脚本将重用相同的数据库连接(只要 ,如果您的数据库位于同一主机上,您应该能够通过使用
mysql_select_db()
函数来使用相同的 mysql 连接。No need to reinvent the wheel. you can use mysql persistent connections to keep connections alive. (http://php.net/manual/en/function.mysql-pconnect.php)
By using persistent connections, your PHP scripts will reuse the same database connections (as long as the database name & credentials are the same)
Also, if your databases are on the same host, you should be able to use the same mysql connection by using
mysql_select_db()
function.