Re: PHP Connections

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]



on 8/5/03 1:44 PM, David Busby at busby@xxxxxxxx wrote:

> Which way to connect is better for my scripts?
> 
> a global
> $db = pg_connect('asdfasdfasdfasdf');
> and every function can have
> global $db;
> at the top?
> 
> or like this?
> 
> function db_handle()
> {
> return pg_connect('asdfasdfasdfasdfadsf');
> }
> 
> and everyplace needed use `db_handle()` so I call pg_exec like
> 
> $rs = pg_exec(db_handle(),"select everything from everywhere"));
> 
> So does that db_handle() make a new connection each time?
> I'm really looking for the way to optimise my connection usage.

I'm more often found asking questions than answering them here, but I think
I'll have a go at this one. To my knowledge, a new connection is a bigger
hit on the server than a query, so from an efficiency standpoint it's best
to have fewer connections, and just make your queries from an existing
connections where possible. So you definitely don't want to be connecting
anew every time you call a function. Some web hosts who allot you a certain
amount of database traffic per plan and charge extra if you have more weight
connections more heavily than queries.

So the first option you have above is the best - the second would indeed
connect every time you called that function.

On my site I have one global include file with the db connection in it, and
just call it in the head section of each page. The code just references the
$db handle where it needs it, rather than connecting again. Even with that,
I keep wondering if it might be better to use a persistent connection that
would last from page to page rather than each page connecting over again.
But the problem there is that I don't necessarily know which page visitors
are going to come in on, so I need to make sure they always get a
connection, and connecting once per page seems like a reasonable compromise.

But hey, come to think of it, maybe I could turn the pg_connect into a
pg_pconnect and just have it check to see if $db already exists before
connecting - that way there'd be only one connection per site visit! Cool,
your question gave me a new idea... :-)


Lynna
-- 
Resource Centre Database Coordinator
Gallery 44
www.gallery44.org



[Index of Archives]     [Postgresql General]     [Postgresql Admin]     [PHP Users]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Databases]     [Yosemite Backpacking]     [Postgresql Jobs]

  Powered by Linux