Page 1 of 1

[SOLVED] PHP Variables Passed Between Functions

Posted: Thu Oct 14, 2004 7:42 pm
by webcan
Hey guys:

I can't seem to get this to work, any idea why?

I have one function whose purpose is to connect to a DB:

Code: Select all

<?php
function connectDB() {
	global $dbsettings;
	$link = mysql_connect($dbsettings["host"], $dbsettings["user"], $dbsettings["pass"]);
	mysql_select_db($dbsettings["dbname"]);
}
?>
I typically call this function from within another function, such as searchDB().

How do I get the $link variable to become accessible from that searchDB function?

The problem is, when I subsequently call disconnectDB():

Code: Select all

<?php
function disconnectDB() {
	mysql_close($link);
}
?>
It comes back and tells me that "Supplied argument is not a valid MySQL-Link resource," referring to $link.

I understand that you declare a variable as "global $var" at the beginning of a function to "import" that varialbe INTO that function, but how do you do the reverse - make a variable accessible OUTSIDE its function?

Thanks,
Peter.

Posted: Thu Oct 14, 2004 8:07 pm
by LostMyLove
try this:

Code: Select all

<?php
function connectDB() {
    global $dbsettings;
     global $link;
    $link = mysql_connect($dbsettings["host"], $dbsettings["user"], $dbsettings["pass"]);
    mysql_select_db($dbsettings["dbname"]);
}
?>

Posted: Thu Oct 14, 2004 8:27 pm
by webcan
That didn't solve it. I still get the same error.

[SOLVED] PHP Variables Passed Between Functions

Posted: Thu Oct 14, 2004 8:33 pm
by webcan
Aha!

That did work, because subsequently when I did 'global $link' in the other functions, it worked.

Thank you!