Re: Using DB in classes
| From: | Darrell Brogdon | Date: | Thu, 24 Jul 2003 17:02:14 +0000 |
| Subject: | Re: Using DB in classes | ||
| References: | 1 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-6798@lists.php.net to get a copy of this message | ||
Yep, thats because you're calling myDbConnect () in every method. You should call it in the constructor once and reference the db handle in all the other methods from there like so:
<?php
require_once "DB.php";
class myClass {
function myClass() {
$this->myDbConnect();
}
function myDbConnect() {
// connects with PEAR::DB
$dsn= "type://user:pass@unix(:/tmp/mysql.sock)/database";
$this->db = DB::connect("$cbDSN");
if (DB::isError($this->db)) {
die ($this->db->getMessage());
}
}
function myMethod1($data) {
$sql = "INSERT record SET column='$data'";
$result = $this->db->query($sql);
if (!$result or DB::isError($result)) {
return false;
} else {
return true;
}
}
// Other methods should follow suit...} ?> -Darrell On Thursday, July 24, 2003, at 12:15 PM, Jackson Miller wrote:
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 {-- Darrell Brogdon Brogdon Internet Services, LLC Phone: 770-918-9042 http://brogdon.biz 1024D/D7FB6981 3CB8 A14D 1662 8351 11F6 40C1 D205 2D97 D7FB 6981function 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 -- PEAR General Mailing List (http://pear.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php