I am trying to write a function that closes the connection created in the following class:
PHP Code:
class dbConnect {
function connect($dataB) {
$conn=mysql_connect("127.0.0.1","username","password") or die (mysql_error());
$db=mysql_select_db($dataB,$conn) or die ("Unable to connect to database1");
}
function closeConnect($conn) {
mysql_close($conn);
}
}
to open a connection, I type:
PHP Code:
$connection1-> new dbConnect();
$sql=$connection1->connect($dataB);
I know the function closeConnect() isn't working. What will make it work?
Well, you need to call it for it to run. If you want it called automatically at the end of execution (which is not necessary btw wince PHP will close the connection for you) you could call it from a destructor method.
Also you are assigning the result of the connect method to a variable but the method doesn't return anything.
You might also want to consider storing the link identifier as a class property instead of passing it around as an argument to methods. Currently you could only ever call closeConnect() from within connect() since the link identifier variable only exists within the scope of that method.
The first rule of Tautology Club is the first rule of Tautology Club.
Here's a quick (and untested) cut at how you might approach it:
PHP Code:
<?php class dbConnect { public $conn; private $dbHost = "127.0.0.1"; private $dbUser = "username"; private $dbPassword = "password"; function connect($dataB) { $this->conn = mysql_connect($this->dbHost, $this->dbUser, $this->dbPassword); if ($this->conn == false) { throw new Exception(mysql_error()); } $db = mysql_select_db($dataB, $conn); if ($db == false) { throw new Exception("Unable to connect to database1"); } } function closeConnect() { if (!empty($this->conn)) { mysql_close($this->conn); } } function __destruct() { $this->closeConnect(); } }
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
PS: You could use the MySQLi extension in object-oriented mode and not have to create your own class.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks