Close connection
Moderator: General Moderators
Close connection
In my project, i've put the code to connect to database (open database connection) in each pages and everything is fine. But i'm quite confius the best way is either i've to put the code to close the connection in each pages or not. Anybody got idea? Thanx..
Sorry for the incomplete question. OK. Let me explain more detail. In my project, let say I have 20 php pages. For all of that 20 pages, I have to retrieve data from database. Thats mean I have to make database connection to every pages. So in all pages, I put this code at the top to make database connection:
My issue is should I put the code to close the database connection at the bottom in all pages? Feel free to ask me if my issue still not clear. Thanx..
Code: Select all
<?php
$db = mysql_connect("localhost", "", "")
or die ("Could not connect to Database");
mysql_select_db ("DBname",$db)
or die ("Could not select database");
?>- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
in the case of mysql, currently, closing the connection is automatic at end of page. However, I believe it's good practice to close it, just in case they decide to turn off the automatic shutdown of the connection in the future.
Closing the connection before page end can also help free up some memory needed for your code, if memory is an issue.
Closing the connection before page end can also help free up some memory needed for your code, if memory is an issue.
- Bill H
- DevNet Resident
- Posts: 1136
- Joined: Sat Jun 01, 2002 10:16 am
- Location: San Diego CA
- Contact:
Unless you are using persistent connections.:
In that case you do not want to close the connection on each page (or at all, let it time out) and, depending on your host and the server configuration, this is much friendlier to the host.
Code: Select all
$Host = "localhost"; // server name
$User = "username"; // database param
$Password = "password"; // database param
$Link = mysql_pconnect($Host, $User, $Password);
mysql_select_db($dbmName, $Link); // link to the main database by default- Bill H
- DevNet Resident
- Posts: 1136
- Joined: Sat Jun 01, 2002 10:16 am
- Location: San Diego CA
- Contact:
Code: Select all
$Host = "localhost"; // server name
$User = "username"; // database param
$Password = "password"; // database param
$Link = mysql_connect($Host, $User, $Password);
mysql_select_db($dbmName, $Link); // link to the main database by default
//code stuff
mysql_close($Link);