开发者

Connecting to MDB2 in PHP object

开发者 https://www.devze.com 2023-03-11 19:23 出处:网络
$dsn=\"mysql://$db_username:$db_password@$db_hostname/$db_database\"; global $mdb2; $mdb2=MDB2::connect($dsn);
$dsn="mysql://$db_username:$db_password@$db_hostname/$db_database";
global $mdb2;
$mdb2=MDB2::connect($dsn);
if (PEAR::isError($mdb2))
{
    die($mdb2->getMessage());
}

I do this to connect to my DB, I put this in a separate php file called Connect.php and require it on all my pages.

However, when I have to query inside a function, I will have to pass $mdb2 to the function as an argument? Is this the right way to do it.

Further, I am writing a class which will query my DB. And I have no idea what to do (I don't wanna pass it as an argument)

Do I hav开发者_如何学Goe to re-establish the connect everytime (ie. write a function for connection)

Can't you make the connection persistent and global?


You can require your file Connect.php on all of your pages, and every function that needs to use the connection can refer to the global variable $mdb2.

For example:

# In file Connect.php

<?php
$dsn="mysql://$db_username:$db_password@$db_hostname/$db_database";
$mdb2=MDB2::connect($dsn);
if (PEAR::isError($mdb2))
{
    die($mdb2->getMessage());
}


#In any other file

<?php
require_once "Connect.php";
getUser($id) {
    global $mdb2;
    $mdb2->query("SELECT ....");
}

Other solution is using a Singleton Class to access the database, so that there is a function that always returns the reference to your $mdb2 variable.

Surely, the discussion Global or Singleton for database connection? is something worth reading.

0

精彩评论

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

关注公众号