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

PHP - JSON empty values in database
Find consecutive repited value in array
Ubuntu Apache PHP - Create and write to an Excel Document
PHP fopen() Cannot Execute Opened Php Extension File
Woocommerce two shipping options at same time
PHP- How to create a text file in network shared folder
not getting response from Mixpanel
input of the form is not updating [duplicate]
How to setup Memcached with failover support in Heroku/PHP 5.6 environment?
Cartesian Product on unknown number of php arrays
How can I repeat IF twice or infinite times in PHP? [duplicate]
How to add extension Add global in twig
PhpStorm: Only Link to Function in included Code
I need help writing a small program to randomly draw entries from a list
URL rewriting doesn't work when web-site is accessed via alias directory
FOSUserBundle overwrite registration but Could not load type error

Categories

HOME
nam
openxml
d3.js
haproxy
bing-search
gallery
ui-automation
migrate
locationmanager
grocery-crud
trace32
xbox360
c#-7.0
jitsi
data-type-conversion
activeadmin
sqlplus
channel
software-packaging
web-push
high-availability
unrar
openbravo
history.js
tortoisehg
social-networking
guice
intune
sql-execution-plan
image-optimization
creation
love2d
twilio-php
installanywhere
macports
text-decorations
microkernel
classnotfoundexception
distributed-caching
word-cloud
spooler
doctrine-extensions
docker-ucp
viewmodel
sonicmq
nusoap
comm
android-sharing
simple-schema
portability
clrs
sesame
emf-compare
business-rules
instafeedjs
haraka
livereload
spring-mongo
node.js-connect
facebook-ios-sdk
android-async-http
gridbaglayout
seadragon
cortana
textpattern
bjam
pythonxy
css-paged-media
vdm-sl
dynamics-ax-2012-r2
embeddedwebserver
ocmockito
dos2unix
fasterxml
device-admin
osascript
.htpasswd
webaii
ctp
pbkdf2
mousemotionlistener
acitree
mp4parser
disjoint-union
xmlwriter
smartfox
arrow
thejit
taskkill
algol68
acpi
navigationcontroller
botnet
git-log
resharper-5.0
oracle-pro-c
dm
data-retrieval
external-sorting

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App