[SOLVED] PHP Variables Passed Between Functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

[SOLVED] PHP Variables Passed Between Functions

Post 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.
Last edited by webcan on Thu Oct 14, 2004 8:33 pm, edited 1 time in total.
LostMyLove
Forum Newbie
Posts: 20
Joined: Mon Sep 27, 2004 12:20 pm

Post 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"]);
}
?>
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

Post by webcan »

That didn't solve it. I still get the same error.
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

[SOLVED] PHP Variables Passed Between Functions

Post by webcan »

Aha!

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

Thank you!
Post Reply