use only one $dbh for several databases?
If you have two databases on the same host, one called blog and one called forum, it seems like you can access both using only one database handle? (in P开发者_开发问答DO)
$dbh=new PDO("mysql:host=$dbHost;dbname=blog", $dbUser, $dbPassword);
This handle is for the database blog, although you can also perform operations on forum using $dbh if you write something like
SELECT website.tableName.fieldName
My questions are:
Is the only reason why you have to specify dbname in $dbh for letting you omit the blog.tableName.fieldName part?
Since my website has two databases, would there be any pros or cons of only using one database handle, rather than creating two handles (obviously one for blog and one for forum)? Possible performance difference?
Does creating a database handle consume any server resources?
- It is usually good practice to keep database specific user on any app you make. I would go as far as calling it necessity. That is the reason of keeping the name of the database necessary in the connection. (Hint for reason behind this: What if someone got your dbms password for one table somehow?)
- I am not very good at this but I do not think its a good idea to keep two separate databases when one can do. Like in your case, you are not using master-slave or anything. So unless you have some physical limit you are trying to make up for, make them into 1 database (use prefixes for table names to avoid name collisions)
- The reason for the previous point comes with this one. Keeping one user for a database or some people even keep two for strange and to some extent justifiable reasons is a safety measure you should follow. For multiple users, you need to make multiple connections, which means for every page load you will be connecting to the dbms twice! simple math 2x load (yes, it eats resources, every single line of code does) Simplifying it, think of a man who needs to walk to the grocery store for everything you ask for, gets only 1 thing at a time. if you give him 2 different grocery stores, the man will need 2x time and energy to do the same work.
- Yes, you can omit it. Or switch with running
USE databasename;
. - Use one handle, seems a waste to make double the connections.
- Yes, hence (2).
精彩评论