MySQL 和PHP:自动连接到数据库或以正确的方式将主机/数据库传递给 MySQL 方法
有谁知道 PHP 中的一种已知方法可以在应用程序在多个主机上使用多个数据库的情况下自动连接到 MySQL 数据库/表?
问题 1:是否有脚本允许根据查询自动连接到必要的主机/数据库?
问题 2:如果上述不可能,是否有已知的方法可以正确传递主机/数据库信息,以确保应用程序在执行查询之前正确连接?
does anyone know of a known method in PHP to auto connect to MySQL db/table in case an app is using multiple databases on multiple hosts?
Question 1: are there scripts around that allow to auto connect to necessary host/DB based on query?
Question 2: if above is not possible, is there a known approach to properly passing host/DB info to make sure app is properly connected before executing the query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该编写一个包装类。这个类将有一个函数
query
。从这里,您有一些选择:如果您使用选项 1 或 2,您可能希望将查询的组成部分拆分为多个参数,因此您的
query
函数看起来更像query($operation, $columns, $表名、$whereClause、$orderBy)
。您还可以添加其他参数,但这只是如何执行此操作的示例。包装类的另一种可能性(这是我更喜欢的方法)是创建该类的实例,每个实例都有自己的 MySQL 连接。只需为您将使用的每个连接创建该类的一个实例,在脚本开头连接到它,然后为您的查询使用正确的实例。例如:
这是 MYSQL.php:
如果您正确使用它,它还会为您清理输入。另一个样本:
You should write a wrapper class. This class will have a function,
query
. From here, you have some options:If you use option 1 or 2, you will probably want to split the components of your query into multiple parameters, so your
query
function would look more likequery($operation, $columns, $tableName, $whereClause, $orderBy)
. There are other parameters you could possibly add as well, but this is just an example of how you could do it.Another possibility with your wrapper class (which is the method I prefer) would be to create instances of the class, each with its own MySQL connection. Just create one instance of the class for each connection you will use, connect to it at the beginning of the script, and just use the correct instance for your query. For example:
Here is MYSQL.php:
It also sanitizes input for you if you use it properly. Another sample: