0

Possible Duplicate:
How to access mysqli connection in another class on another page?

I have a PHP class for connecting to a MYSQLi database and I want to use this class within another class to create a prepared statement and display some info from a database.

Is this possible at all?

<?php 

    class database {

        public $host = "localhost";
        public $user = "root";
        public $password = "root";
        public $name = "store";


        public function connect() {

            $connect = new mysqli($this->host, $this->user, $this->password, $this->name);

            if($connect->connect_errno > 0){
                die('Unable to connect to database [' . $connect->connect_error . ']');
            }

        }

    }


    class products {

    // In here I want to use a MYSQLi prepared statment to show some information
    // from the database details in the class above

    }



    $database = new database();
    $database->connect(); 

    ?>

Thanks in advance!

Community
  • 1
  • 1

1 Answers1

0

Instead of connecting in the other class, you have to connect somewhere in bootstrap, getting class instance into variable. Then you'll be able to either pass this variable into constructor parameters or simple use

global $db;
$this->db = $db;

in constructor

By the way, I see no use for separate connect() method. Why not to connect right in the constructor?
Also let me suggest you not to use die() but trigger_error() (or exception) instead.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345