View Full Version : mysqli_connect with arrays not in a function

10-09-2006, 05:14 AM
Ok, i may be thinking of Java or i may be wrong but can't you call arrays from inside functions without passing them in? Like this

$food['soup'] = "wet";
$foot['carrot'] = "hard";

function makeFood(){
... play with the arrays or whatever

doesn't that work? Or is there a way to pass in arays with out having to pass them in.... man its late, ha.

This is what i'm trying to do. I've setup my database variables in a file called conf.php and thers also a function in there called goDB(); goDB() connects to my database using the variables from the array in the file. I call goDB() from other files by importing conf.php into them. I want to be able to just call goDB() and dont worry about passing in the array.

Thanks for the help. Oh, and after thinking about it, no i was wrong, in Java arays are special because they don't create a copy of themselves in a function when passed in but you still need to pass them in, I belive PHP has the same rule. so I'm going at this wrong, obviously.

thanks for the help.

10-09-2006, 06:02 AM
You can, has to do with variable scope. In your function either use the global keyword or use $GLOBALS.


function makeFood()
global $food, $foot;
echo '<pre>';
echo '</pre>';

// or
function makeFood()
echo '<pre>';
echo '</pre>';


Good luck;

10-09-2006, 06:16 AM
Thank you very much. that is very helpful but now i'm getting errors as if I made my arrays wrong, i don't think I have but heres what they look like

global $gs_database['host'] = "localhost"; // database host ( for example 'localhost' )
global $gs_database['database'] = "guildspace"; // database name
global $gs_database['username'] = "root"; // database user
global $gs_database['password'] = ""; // database user's password

Heres the error

Parse error: parse error, unexpected '[', expecting ',' or ';' in conf.php on line 3

note, that first line i posted is line 3.

I've also tried telling my function to use thoes vars as globals as the link you gave me said by using this line:

global $gs_database['host'],$gs_database['username'],$gs_database['password'],$gs_database['database'];

and it still give me the same error.

10-09-2006, 06:21 AM
Close, use global on the array itself, not individual elements:

global $gs_database;
$gs_database['host'] = "localhost"; // database host ( for example 'localhost' )
$gs_database['database'] = "guildspace"; // database name
$gs_database['username'] = "root"; // database user
$gs_database['password'] = ""; // database user's password

Good luck;

10-09-2006, 06:24 AM

Thank you so much, it works perfectly now. And puting in global $gs_database; is so much easier!

I'll get a hang of this PHP stuff sooner or later.

10-09-2006, 06:25 AM
Cool, you're welcome :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum