Web Hosting Talk







View Full Version : mysql connections with php


misti
12-10-2004, 06:55 AM
Hi!
I have written a php script that it is a kind of a directory. The script connects to a db, presents some data to the user and is composed of several individual files. Each file includes the db.php file which opens a database connection. At the end of each file, I close the db connection. Is this the right approach?
My thoughts are that it takes time to open a new connection everytime the user views another page. Is it possible to open a single db connection for as long as the user is surfing my site?
What is the best approach?

nnormal
12-10-2004, 11:42 AM
I dont think opening the connection is really anything to worry about performance wise. Most of the problems with DB code tends to revolve around sloppy queries or bad DB design. If you are talkin MySQL, PHP automatically closes the connection after it's done parsing the page anyways.

misti
12-10-2004, 12:01 PM
yes I am talking about mysql.
So i dont need to do the following?

mysql_free_result($result);

mysql_close($link);

nnormal
12-10-2004, 12:05 PM
it doesnt hurt


mysql_close() closes the connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ThorN
12-10-2004, 12:17 PM
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.

As long as you don't close the connection PHP will automatically re-use the last open connection. You should always use the mysql_free_result() as soon as possible because it frees memory and it is better to do things expicitly rather than implicetly. However to get your desired effect, do not call mysql_close() so that PHP will re-use the connection.

I prefer to use object wrappers around database calls to handle mundane calls and to ease portability to other databases. ADO DB is a good object wrapper (http://adodb.sourceforge.net/).