Why specify an explicit database connection?
I am making a simple blog for myself and while reading through the 开发者_运维百科PHP manual, I found this http://us2.php.net/manual/en/function.pg-query.php
It says
resource pg_query ([ resource $connection ], string $query )
...
Note: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.
Why is it not ok to just use the last connection? I never plan on having more than 1 connection open per PHP script, so how would this ever cause bugs for me?
Hah. "I never plan on having more than 1 connection open per PHP script."
I remember the last time I said that. It was back in 'ought three. I was a young whippersnapper then, much like yourself. Full of spit and vinegar. Why do something if I don't have to? That was the prevailing wisdom in our little dot-com startup. "Just get it done!" we'd shout. Also, we wore onions on our belts.
Well... time came that I added a quick little statistics database in to the main site. Nothing special, just wanted some stats tracked separately. I figured I'd re-use the database wrapper. It was a good wrapper for it's time! Abstracted out all the database functions I'd need. But as soon as I added it in there, some wacky things started happening. It didn't make sense. I had two separate database wrapper objects... two separate connections! How could they affect each other? But then users would be logged out randomly. Sessions would fail. Sometimes a key update would go bad. Some queries ran on the wrong databases. Dogs and cats started living together! It was mass hysteria!
If only I had specified that connector originally. If only I had kept them specific, so pg_query would know which one to use. So much data loss could have been prevented. So many good tuples... so much good data. Lost. Lost...
*sniff *
This is to accommodate those who need explicit calls to various databases. If you don't, ignore it :) Some scripts work on local and remote databases, and yet others work on multiple local or multiple remote databases.
Perhaps it is due to the order of arguments? If it was regarding a recommendation to explicitly use a connection resource, the same note would be on mysql_query(). Unless there is something specific to PostgreSQL I am unaware of.
In short, I don't see any problem omitting the connection argument for single connection applications.
精彩评论