什么最好的方法访问数据库在一个PHP类?What the best way to access the database inside a class in PHP?
I have a session class that needs to store session information in a MySQL database. Obviously I will need to query the database in the methods of this class. In general I may need to connect more than one database simultaneously and may or may not be connected to that database already.
Given that, what's the best way to access databases for the session class or any class for that matter. Would creating a class to manage connections make sense?
I'd advise to check out this presentation, among other things it talks about best practices when accessing database:
(原文：Nice link, thanks.)tereško的回复:链接是坏了。
(原文：link is broken.)
Database Connections are a prime example of when and where you can safely use a Singleton pattern; however, if you know that the Session Object will be a global object and it will be the only place that you need to create Database Connections, you could pretty safely store the db connections as instance members of the Session Class.
(原文：Yeah, I use a singleton database class for all of my DB work.)
Yes, I would use a DBAL. Either you can write your own, or you can use an existing solution like PDO. Even if using an existing solution, you may want to write a wrapper class that uses the singleton pattern so that a single connection can be shared with all parts of your code.
(原文：What about if I need to be connected to database A and database B at the same time? Would that be a singleton factory? Or would I need another wrapper around the singletons?)Lucas Oman的回复:我会写两个单例类的,,只有改变DB的凭证。独立是很重要的,因为它创造了一个全球性的,所以你只需要每个数据库连接一次。
(原文：I would write two more classes that extend the singleton, and only change the DB credentials. The singleton is important because it essentially creates a global, so you only need to connect once to each DB.)
- 我怎么能在MySQL在两列布尔逻辑吗?How can I do boolean logic on two columns in MySQL?
- 我怎么做布尔逻辑在MySql的两列,其中一个是一个Varchar吗?How do I do boolean logic on two columns in MySql, one of which is a Varchar?
- 我如何创建一个有序列表最常见的子字符串在MySQL varchar列?How can I create an ordered list of the most common substrings inside of my MySQL varchar column?
- 简单随机样本从一个Sql数据库Simple Random Samples from a Sql database
- 查询优化技术?(关闭)Query optimization techniques? [closed]
- 什么最好的方法访问数据库在一个PHP类?What the best way to access the database inside a class in PHP?
- MySqlCommand参数不工作MySqlCommand Parameter not Working
- 重装MYSQL(windows)——怎么去旧的数据与新安装吗?Re-installing MYSQL(windows) - How to get to the old data with the new install?
- 做一个mysql表中的ID auto_increment(事后)make an ID in a mysql table auto_increment (after the fact)
- 我如何升级mysql ?How do I upgrade mysql?
- 做数值主键删除记录在数据库中得到重用未来新记录?Do numerical primary keys of deleted records in a database get reused for future new records?