Jump to content

Archived

This topic is now archived and is closed to further replies.

micah1701

calling $var from include() file

Recommended Posts

I keep a config.inc file for my application which includes a var called $tablename which holds the string value of, you guessed it, the table name used throughout the applications.

on each page, I include() the config file and can call the $tablename var in my queries.
example:

[!--coloro:#FF0000--][span style=\"color:#FF0000\"][!--/coloro--]mysql_query("SELECT * FROM $tablename");[!--colorc--][/span][!--/colorc--]

This is working on all of my pages as it should; HOWEVER, it is failing when I include another page (called "functions.php") and try to run a function off that page.
example:

functions.php page has this function:
[!--coloro:#FF6600--][span style=\"color:#FF6600\"][!--/coloro--]function runQuery{
$result = mysql_query("SELECT * FROM $tablename");
return $result;
}[!--colorc--][/span][!--/colorc--]

index.php has this code:
[!--coloro:#33CC00--][span style=\"color:#33CC00\"][!--/coloro--]include('config.inc');
include('function.php');
$result = runQuery();[!--colorc--][/span][!--/colorc--]

I get no result because the query in the function does not recognize the tablename var which is included from the previously loaded config file.

what am I not understanding here?
Thanks for your thoughts!

Share this post


Link to post
Share on other sites
You need to pass the $tablename variable into your function.

This should work.


[code]
function runQuery($the_tablename)
{
$result = mysql_query("SELECT * FROM $the_tablename");
return $result;
}
[/code]


[code]
$result = runQuery($tablename);
[/code]

alternatively, it could just need this;

function runQuery()
{
$result = mysql_query("SELECT * FROM $tablename");
return $result;
}

Share this post


Link to post
Share on other sites
That solved it! Thanks wisewood. you [i]ARE [/i]very wise.

I had just assumed that the variable would be available to the function.

Thanks again!

Share this post


Link to post
Share on other sites
or what you could do instead is inside your function declare it as a global variable, instead of passing it as an argument:

[code]
function runQuery()
{
global $tablename;

$result = mysql_query("SELECT * FROM $tablename");
return $result;
}
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.