Using DB in classes
| From: | Jackson Miller | Date: | Thu, 24 Jul 2003 16:15:26 +0000 |
| Subject: | Using DB in classes | ||
| Groups: | php.pear.general | ||
| Request: | Send a blank email to pear-general+get-6793@lists.php.net to get a copy of this message | ||
I have been teaching myself OOP and using it on a regular basis, but there are
some things that I think I might not be doing right. One example of this is
my database connection from within classes using DB. All the tutorials I
have seen for using DB are for procedural code and not OOP, so what I am
doing works, but was learned through trial and error. However, my method
isn't allowing me to disconnect from the database, and I am creating a new
connection for each method call.
Here is what I am doing, any suggestions as to what I am doing wrong will be
greatly appreciated.
<?php
require_once "DB.php";
class myClass {
function myClass() {
// constructor does nothing
}
function myDbConnect() {
// connects with PEAR::DB
$dsn= "type://user:pass@unix(:/tmp/mysql.sock)/database";
$db = DB::connect("$cbDSN");
if (DB::isError($db)) {
die ($db->getMessage());
}
return $db;
}
function myMethod1($data) {
// connect to the db
$db = $this->myDbConnect();
$sql = "INSERT record SET column='$data'";
$result = $db->query($sql);
if (!$result or DB::isError($result)) {
return false;
} else {
return true;
}
}
function myMethod2($data) {
// connect to the db
$db = $this->myDbConnect();
$sql = "UPDATE record SET column='$data'";
$result = $db->query($sql);
if (!$result or DB::isError($result)) {
return false;
} else {
return true;
}
}
}
?>
My code may then be:
<?php
$obj = new myClass;
// try to insert, if it fails then update
if (!$obj->myMethod1($data)) {
$obj->myMethod2($data);
}
?>
The problem is that created two connections to the database (I think), and the
connection is left to timeout.
Thanks in advance,
-Jackson