views:

45

answers:

2

Ok, I am completely baffled.

I am setting up an OO site. I have a class that defines all my database params, as follows:

$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";

The class is being instantiated correctly and the values show up in pages that appear after this class has been loaded.

BUT, when I try to connect to this database from a different class, it does not connect. Here's how I am connecting:

$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);

Everything works fine if I take out the user, pw and name variables and hard code in the correct values, but if any of them is referenced using the db construct, no connection happens. Again, the db construct appears just fine on other pages and I am seeing the variable values being presented correctly. The $db->host variable, however, always works.

Here's is how I am constructing the db class:

class database {
    var $host;
    var $name;
    var $user;
    var $pw;

    function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
        $this->host =   $host;
        $this->name =   $name;
        $this->user =   $user;
        $this->pw =     $pw;
    }
}

and then I of course do

 $db = new database();

Thanks in advance for any help!

+2  A: 
  1. Don't use PHP4
  2. Why don't you just use PDO
  3. What's the point of storing password or username as a object property?
  4. Probably the problem is a $db variable scope

How to fix all of that?

class MyClass {
    protected $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function doSth() {
        $this->db->query('..');
    }
}

$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$obj = new MyClass($db);
$obj->doSth();
Crozin
I didn't realize that I was using PHP4 code... thanks for the info!
Gary
FYI... in the code sample above, db_name should be dbname... at least for mySQL anyway. Took me quite a while to figure that out!
Gary
Oh.. my bad - corrected.
Crozin
A: 

I think u are not passing parameters when creating object for initializing the database class constructor.

try using

$db=new database("localhost","dbname","user","password");

and then create the class as

class database {
   var $host;
   var $name;
   var $user;
   var $pw;

       function __construct($host , $name , $user , $pw ){
        $this->host =   $host;
        $this->name =   $name;
        $this->user =   $user;
        $this->pw =     $pw;
    }

Also include this class as file if written separately and for connection u can now write

$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);

Hope this helped :)

Anurag