ds78662302 2016-11-19 07:46
浏览 30

PHP PDO新连接:选择数据库有什么影响?

When making a new connection with PDO:

$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

It appears you have to specify a database in the DB_DSN, e.g.

mysql:dbname=mydatabase

I have however just discovered that this does not limit subsequent queries using this connection to just this database. Any other databases that DB_USERNAME has permissions for can be used. All it appears to do is specify a default.

It has revealed for me that sometimes, queries were not being specific enough and thus a risk that a table in the wrong database would be accessed.

I am thinking I should create a dummy database, make all connections to that database, thus forcing all queries to include the database name explicitly.

Or: is there a way to make a connection exclusive to a given database?

What is best practice here?

  • 写回答

1条回答 默认 最新

  • doulin4844 2016-11-19 08:04
    关注

    Options on that:

    • use db name in querys SELECT * FROM dbname.tblname
    • create an sql mapper class that selects the database before each query new SQLMapper($databasename,$connection); & mysql_select_db($this->dbname,$this->con) in query() method
    • use DOCTRINE or something like that, they handle that for you
    • give an dbuser only access to one database (forces devs to use the right instance & no db change)

    Use what is usefull in given cases, there is no best solution.

    Its mostly about how much control over the code in your application you have.

    If rules are followed, then everything should be fine.

    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染