Solved

PHP5: when do I close my database object connection?

Posted on 2014-11-04
3
89 Views
Last Modified: 2014-11-04
Hello Experts,

In the sample database code below, when do I close the database obj connection?
I use the object to query the db throughout the session....

//***** index.php 

require_once 'Database.php';

$db = new Database();
$db->getInstance();

$db->testQuery();
$email = $db->testQuery();


//***** Database.php

class Database extends mysqli_stmt {

	//set db access data
	private $server = "localhost";
	private $user = "test";
	private $pass = "test";
	private $db = "test";
	
	private $instance;

	function getInstance(){
	
		$db = new mysqli ( $this->server, $this->db, $this->pass, $this->user );
	
		if ($db->connect_error) {
			die('Connect Error (' . $instance->connect_errno . ') ');
		} else {
			$this->instance = $db;
		}		
	
		return $this->instance;
	}
	
	function testQuery( $name ){
		
		$stmt =  $this->instance->stmt_init();
		
		$query = "SELECT `email` FROM customers WHERE Name=?";
		if ($stmt->prepare($query)) {		
			$stmt->bind_param("s", $name);
			$stmt->execute();
			$stmt->bind_result( $email );
			$stmt->fetch();
			$stmt->close();
		}
		
		return $email;
		
	}
	
	function dbClose(){
		$this->instance->close();
	}
	
	
}//END OF CLASS...

Open in new window


Regards,
0
Comment
Question by:epifanio67
3 Comments
 
LVL 58

Accepted Solution

by:
Gary earned 250 total points
Comment Utility
You don't need to, they close when the page finishes execution.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
Don't even bother.  The PHP "cleanup" routines will take care of that for you.
0
 

Author Closing Comment

by:epifanio67
Comment Utility
Thank you experts... just wanted to make sure...

Regards,
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now