Jump to content

Archived

This topic is now archived and is closed to further replies.

n8w

the right way to connect and close DB connections

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

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites
Hey Jasper .. great catch .. I think that was probably the problem

thanks!

Share this post


Link to post
Share on other sites

×

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.