Jump to content

the right way to connect and close DB connections


n8w

Recommended Posts

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
[code]
<?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");
?>
[/code]

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

and then at the end of my page I have this

[code]
mysql_close();
[/code]

Thanks for your help
Link to comment
Share on other sites

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?
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.