Server overload and closing connections

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Matt Phelps
Forum Commoner
Posts: 82
Joined: Fri Jun 14, 2002 2:05 pm

Server overload and closing connections

Post by Matt Phelps »

I'm programming my first site with php/mySQL but I have a suspicion that the code I'm writing isn't very server friendly.

In some scripts I'm accessing the database several times and various different tables and I'm wondering about how server intensive that would be. I can't think of a better way of doing it but it does concern me.

Also I am including the following file at the top of every script:

Code: Select all

<?php

$dbh = @mysql_pconnect("localhost");

if (!$dbh)
&#123;
  echo("<H3>Failed to connect to database server</H3>");
  exit();
&#125;

if (! @mysql_select_db("project") )
&#123;
  echo("<H3>Failed to find your database</H3>");
  exit();
&#125;

?>
...and using that to access the database. My knowledge on the different ways of connecting to mySQL is a bit thin but is p_connect the best way to do this? I don't have any commands anywhere in my scripts to close the connection later on - should I have? And how would I call that?

Thanks!
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

In using mysql_pconnect() you are opening a connection to the database server that will not be closed when the script ends. More information about persistent database connections is available on the php.net website: http://www.php.net/manual/en/features.p ... ctions.php

Whether persistent connections are good or bad very much depends on the server set up but a lot of hosts do disallow persistent connections or strongly discourage them.

If you use mysql_connect() then the connection to the database is closed when the script is executed or if you like you can use mysql_close() to end the connection before then. Connections opened using mysql_pconnect() are unaffected by mysql_close().

AFAIK server load will depend on what kind of queries you are running and how many. But I'm sure someone else can answer that question better.

Oh and you can simplify your database connection code like so,

Code: Select all

<?php 

$dbh = @mysql_pconnect('localhost') or die('<H3>Failed to connect to database server</H3>'); 
@mysql_select_db('project') or die('<H3>Failed to find your database</H3>'); 

?>
Mac
Matt Phelps
Forum Commoner
Posts: 82
Joined: Fri Jun 14, 2002 2:05 pm

Post by Matt Phelps »

Thanks, that's a big help. :)
Post Reply