best way to have a database connection

best way to have a database connection

am 24.11.2005 19:22:08 von Bruintje Beer

Hi,

I have a question about making a database connection (MySQL). In my php
scripts you have a lot of queries to make. Wat is best to do

- Make every time a new connection whenever you execute a query
- Keep the connection, how do you save the connection. Do you need include
file i.e. include('database.php') in every script or include_once
('database.php')

thanks

Re: best way to have a database connection

am 24.11.2005 21:42:59 von zeldorblat

When you open a connection using mysql_connect(), it will first check
if there's an open connection with the same parameters (username,
password, dbname, host, etc.). If it finds one, it will just reuse the
existing connection (even though you get a different link identifier --
I think).

Of course there's a little bit of overhead to check if the connection
already exists, but this is a lot faster than opening a completely new
connection.

I wouldn't worry too much about opening connections everytime, but if
you want to be really slick you can wrap your database connection with
an object that is also a singleton (at most one instance can ever
exist). For instance, my database class has a static method called
get(). If the object already exists, he just returns it, otherwise he
creates a new one and saves it. So, no matter what scope I'm in
(global, class, function, etc.) I can always say $db = DB::get() and
know that it will reuse the existing object.

Of course you can also have your database.php just make a connection at
the top of every page then reuse that connection throughout the script.
Unfortunately that will only work inside the scope in which the file
was included.