php


When Should I Be Closing My DB Connection In My Class


I have the following class that handles most of my database queries, prepared statements,etc. Below is just a sample of the class I have.
PhP (database.php)
class Database{
public $mysqli;
function __construct(){
// Open the connection to the DB on construct
$this->open_connection();
}
private function open_connection(){
$this->mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die("Database connection failed: " . mysqli_connect_error() . " ( " . mysqli_connect_errno() . " ) ");
}
}
/*
* Creates a user
*/
public function create_user($username, $password){
$stmt = $this->mysqli->prepare("INSERT INTO Users(username,password,dateCreated) VALUES(?,?,NOW())");
$password = $this->hash_password($password);
$stmt->bind_param("ss", $username, $password);
if( !$stmt->execute() ) :
$error = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
endif;
$stmt->close();
return $error;
}
// ....
}
$db = new Database();
Because I am instantiating that class every time on page load when I am requiring that file, how should I go about closing my connection to the database? Can I just leave it open?
You can leave it open because the connection will be closed whenever your script finishes execution anyway. The PHP website on mysqli_close provides the following information on why it's recommended to close the connection anyway:
Open non-persistent MySQL connections and result sets are
automatically destroyed when a PHP script finishes its execution. So,
while explicitly closing open connections and freeing result sets is
optional, doing so is recommended. This will immediately return
resources to PHP and MySQL, which can improve performance. For related
information, see freeing resources
Always: Close all resources you don't need anymore as soon as possible. You can't leave it open until your next page is requested because it terminates anyway as soon as your server finished serving a particular page.
When browsing to another page, you will have to open the connection again anyway. That's where connection pooling comes in handy: https://dev.mysql.com/doc/apis-php/en/apis-php-mysqlnd-mux.connection_pool.html

Related Links

Laravel 4 - PHP-FFMpeg - progress
Is this a good idea: PHP process for each user that logs on
Minus two dates to get the difference in months [duplicate]
Is there any way to detect which hardware the input came from in web programming?
How to make regex match space OR end of string?
Working Of Paypal Rest API
How make my menu active class
regular expression basics - [^.] [duplicate]
PHP JSON array from query
REST API in Laravel when validating the request
Pass $.variable in url
PHP Multilanguage site
Not able to access nested Object elements
Wordpress: Adding an extra folder name in the url before all posts
nth-child dont work when i add a href
When my controller function loads a view, the URL has the controller name and function still in the URL. How can I get rid of this?

Categories

HOME
libgdx
blast
focus
operating-system
code-formatting
ant
risk-management
ios-simulator
bing-search
share
fullcalendar-scheduler
texas-instruments
rest-assured
closures
gravity
jitsi
coreldraw
sybase-ase
backendless
jstree
managed-c++
dnsmasq
substance
guice
premake
wampsharp
image-optimization
winrm
custom-keyboard
db2-luw
subclassing
ftp-server
recovery
sbjson
export-to-pdf
viewcontroller
latexml
type-inference
zend-form
deployd
hibernate-ogm
dblink
mechanicalturk
front-camera
d3v4
livecycle
pyaudio
carmen
xcode8-beta4
maven-release-plugin
verisign
google-maps-api-2
screen-orientation
gitlab-omnibus
embeddedwebserver
angular-amd
maven-shade-plugin
phonegap-facebook-plugin
screwturn
.htpasswd
hyperloglog
reference-counting
webaii
gpu-programming
iosched
spring-security-acl
apache-shindig
non-ascii-characters
stty
postgres-xc
ax
session-0-isolation
jquery-dialog
kaazing
jdom
fbml
servercontrol
glassfish-esb
data-dump
getopts
startupscript
channelfactory
hungarian-notation
uninstaller
eventaggregator
html-components
index.dat
service-factory

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App