zend 数据库连接
在我们的一个项目中,application.ini 中指定的数据库连接是
resources.db.adapter = Mysqli
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = ''
resources.db.params.dbname = zf_tutorial
但我需要从另一个文件调用主机、用户名、密码和数据库名。怎么办?
In one of our project the database connection specified in application.ini is
resources.db.adapter = Mysqli
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = ''
resources.db.params.dbname = zf_tutorial
But I required to call the host, username, password and dbname from another file. how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,在 application.ini 中设置数据库后,调用默认适配器就很简单了
$db = Zend_Db_Table::getDefaultAdapter();
将
resources.db.isDefaultTableAdapter = true
添加到 application.ini 可确保您调用正确的适配器。在很多情况下,这可能无法正常工作,其中大多数涉及引导。
usually with your database setup in the application.ini calling the default adapter is trivial
$db = Zend_Db_Table::getDefaultAdapter();
adding
resources.db.isDefaultTableAdapter = true
to the application.ini makes sure you're calling the correct adapter.There are very situations where this may not work properly and most of them involve bootstrapping.
通常,与数据库的连接在index.php中设置:
在此代码中$adapter和$params是硬编码的。您可以从自定义文件中获取 $adapter 和 $params。
Usually, connection to the DB sets up in index.php:
In this code $adapter and $params are hardcoded. You can get $adapter and $params from your custom file.
这里接受的答案不是获取 db 对象的好方法,它应该像您最初所做的那样在 application.ini 中设置。
如果您想获取 db 对象的另一个实例,您有多种选择;您可以按照@RockyFord的建议进行操作,或者您可以从任何控制器获取数据库对象,如下所示:-
如果您想更进一步并有权访问 连接详细信息(我无法想象为什么你会再次需要它们)您可以像这样从 db 对象获取它们:-
或者确实:-
这将为您提供一个包含连接数据的数组,您可以尝试这样做并执行
var_dump($dbConfig);
来查看细节。如果需要的话,这是一种更可靠的访问数据库对象的方法,尽管如果您需要在多个地方执行此操作,特别是在访问连接详细信息时,我会仔细研究您的整体代码设计如此处所述。
The accepted answer here is not a good way to get the db object, it should be set up in application.ini as you were doing originally.
If you want to get another instance of the db object you have several options; you can do as @RockyFord suggests, or you can get the db object from any controller like this:-
If you want to go further and have access to the connection details (I can't imagine why you would need them again) then you can get them from the db object like this:-
or indeed:-
Which will give you an array containing the connection data, you can try this and do a
var_dump($dbConfig);
to see the details.This is a much more robust way of accessing the db object if you need to, although I would take a long hard look at your overall code design if you need to do this in more than one place, especially if you are accessing the connection details as described here.