Jump to content


Photo

the right way to connect and close DB connections


  • Please log in to reply
2 replies to this topic

#1 n8w

n8w
  • Members
  • PipPipPip
  • Advanced Member
  • 123 posts

Posted 05 March 2006 - 02:38 PM

I have been getting an error lately on my site that says too many connections are open to the database

I think this is because I am not properly opening and closing my db connections ..

is there anything I need to do to my code?

connection script
<?php
$usr = "username";
$pwd = "password";
$db = "database_name";
$host = "localhost";
$cid = mysql_connect($host,$usr,$pwd);
if (!$cid) {
   die(mysql_error());
}
mysql_select_db($db,$cid) or die ("Could not open database");
?>

then when I query the database I have this
 # execute SQL statement
    $retid = mysql_db_query($db, $sql, $cid) or die(mysql_error());
# check for errors
if (!$retid) {
 die(mysql_error());
    } else {

and then at the end of my page I have this

mysql_close();

Thanks for your help

#2 JasperBosch

JasperBosch
  • New Members
  • Pip
  • Newbie
  • 8 posts
  • LocationApeldoorn, The Netherlands

Posted 05 March 2006 - 07:22 PM

Hi n8w,

Do you have any reason to use mysql_db_query instead of mysql_query?

$cid = mysql_connect($host,$usr,$pwd); already creates a connection to your database, the mysql_db_query creates a new connection to your database and you won't use the connection you already made.
Read the reference: [a href=\"http://www.phpfreaks.com/phpmanual/page/function.mysql-db-query.html\" target=\"_blank\"]mysql_db_query[/a] and [a href=\"http://www.phpfreaks.com/phpmanual/page/function.mysql-query.html\" target=\"_blank\"]mysql_query[/a]

I never close a databaseconnection, it is closed on termination of the script. I think?


#3 n8w

n8w
  • Members
  • PipPipPip
  • Advanced Member
  • 123 posts

Posted 05 March 2006 - 09:56 PM

Hey Jasper .. great catch .. I think that was probably the problem

thanks!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users