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,
[syntax=php]
$mysql = new mysql("localhost", "root", "", "table");
$mysql->query("SELECT `stuff`, `that`, `i`, `need` FROM `StuffAndJunk`");
[/syntax]
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.
OOP Multiple connects, don't want.
Re: OOP Multiple connects, don't want.
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
![Wink ;)](./images/smilies/icon_e_wink.gif)
Re: OOP Multiple connects, don't want.
jacek wrote:That's how I intended it to be usedWhy cant you do that ?
It doesn't make sense in my head, I tried it,
[syntax=php]
include("core/database.class.php");
$mysql = new mysql("localhost", "root", "", "table");
include("core/navigation.inc.php");
include("core/header.inc.php");
[/syntax]
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
[syntax=php]
public function GetNav() {
$mysql->query("SELECT
`page_id`,
`page`
FROM `navigation` ORDER BY `order` ASC
");
}
[/syntax]
Re: OOP Multiple connects, don't want.
The connection variable is in global scope, so in functions you need to do
[syntax=php]public function GetNav() {
global $mysql;
$mysql->query("SELECT
`page_id`,
`page`
FROM `navigation` ORDER BY `order` ASC
");
}[/syntax]
[syntax=php]public function GetNav() {
global $mysql;
$mysql->query("SELECT
`page_id`,
`page`
FROM `navigation` ORDER BY `order` ASC
");
}[/syntax]
Re: OOP Multiple connects, don't want.
Aah, now it works ![Very Happy :D](./images/smilies/icon_e_biggrin.gif)
![Very Happy :D](./images/smilies/icon_e_biggrin.gif)