OOP Multiple connects, don't want.

Ask about a PHP problem here.
Post Reply
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

OOP Multiple connects, don't want.

Post 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.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: OOP Multiple connects, don't want.

Post 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 ?
Image
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: OOP Multiple connects, don't want.

Post 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
    ");
}
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: OOP Multiple connects, don't want.

Post 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
   ");
}
Image
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: OOP Multiple connects, don't want.

Post by EcazS »

Aah, now it works :D
Post Reply