开发者

php pdo connection scope

Hey guys I have a connection class I found for pdo. I am calling the connection method on the page that the file is included on. The problem is that within functions the $conn variable is not defined even though I stated the method was public, and I was wondering if anyone had an elegant solution other then using global in every function. Any suggestions are greatly appreciated.

CONNECTION

class PDOConnectionFactory{
    // receives the connection
    public $con = null;
    // swich database?
    public $dbType  = "mysql";

    // connection parameters
    // when it will not be necessary leaves blank only with the double quotations marks ""
    public $host    = "localhost";
    public $user    = "user";
    public $senha   = "password";
    public $db  = "database";

    // arrow the persistence of the connection
    public $persistent = false;

    // new PDOConnectionFactory( true ) <--- persistent connection
    // new PDOConnectionFactory()       <--- no persistent connection
    public function PDOConnectionFactory( $persistent=false ){
        // it verifies the persistence of the connection
        if( $persistent != false){ $this->persistent = true; }
    }

    public function getConnection(){
            try{
                // it carries through the connection
                $this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha, 
                array( PDO::ATTR_PERSISTENT => $this->persistent ) );
                // carried through successfully, it returns connected
                return $this->con;
            // in case that an error occurs, it returns the error;
            }catch ( PDOException $ex ){  echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }

    }

    // close connection
    public function Close(){
        if( $this->con != null )
            $this->con = null;
    }

}

PAGE USED ON

include("includes/connection.php");

$db = new PDOConnectionFactory();
$conn = $db->getConnection();

function test(){
try{
    $sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sq开发者_如何学JAVAl);
$result=$stmt->execute();

}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();


You can declarate database class where you carrying conn pdo class, then you don't must duplicates instaces of this. And all database operations you can doing by this class. I mean my answer is what you searching.

But i see, you using only PDO hadle class in Product Factory pattern. You can use normal full database support class under PDO (includes queryies execution from one function) and without this design pattern when you don't want to use many database connectors engines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜