Page 1 of 1

OOP Multiple connects, don't want.

Posted: Sun Jun 05, 2011 5:24 pm
by EcazS
Let's say I have a file called header.php and in that file I have a function that connects to a MySQL database and gets some info from a table and then outputs it.

Now, what if I have another file called navigation.php and in that file I have a function that connects to the same MySQL database and gets some info from a table and then outputs it.

I then include both files in another file so I'm actually connection twice, now, how could I avoid connection multiple times?
I'm using this to connect and fetch stuff,
$mysql = new mysql("localhost", "root", "", "table");
$mysql->query("SELECT `stuff`, `that`, `i`, `need` FROM `StuffAndJunk`");
I'm guessing I can't just throw the connect on the top of my "main" file and still use the fetch inside the other files classes and functions.

Re: OOP Multiple connects, don't want.

Posted: Sun Jun 05, 2011 5:58 pm
by jacek
EcazS wrote:I'm guessing I can't just throw the connect on the top of my "main" file and still use the fetch inside the other files classes and functions.
That's how I intended it to be used ;) Why cant you do that ?

Re: OOP Multiple connects, don't want.

Posted: Sun Jun 05, 2011 8:06 pm
by EcazS
jacek wrote: That's how I intended it to be used ;) Why cant you do that ?
It doesn't make sense in my head, I tried it,
    include("core/database.class.php");

    $mysql = new mysql("localhost", "root", "", "table");

    include("core/navigation.inc.php");
    include("core/header.inc.php");
but it gives me,

Notice: Undefined variable: mysql in C:\xampp\htdocs\PhpStorm Projects\OOP\core\navigation.inc.php on line 17

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\PhpStorm Projects\OOP\core\navigation.inc.php on line 17

Navigation.inc.php
public function GetNav() {
    $mysql->query("SELECT
            `page_id`,
            `page`
        FROM `navigation` ORDER BY `order` ASC
    ");
}

Re: OOP Multiple connects, don't want.

Posted: Sun Jun 05, 2011 8:53 pm
by jacek
The connection variable is in global scope, so in functions you need to do
public function GetNav() {
    global $mysql;

    $mysql->query("SELECT
           `page_id`,
           `page`
       FROM `navigation` ORDER BY `order` ASC
   ");
}

Re: OOP Multiple connects, don't want.

Posted: Sun Jun 05, 2011 9:10 pm
by EcazS
Aah, now it works :D