Get a VAR from one FUNCTION into another?

Hey Everyone,

Im new here & also new to PHP.

I’m building some small projects at the moment to enhance my knowledge of php as i would love to learn the art of building advanced php web apps.

Ill now get to the point: I have setup a way i want my database to gather info, if its useless or if there is a better way please tell me! But basically what i need is to send a $var to a function but the $var is a var from another function. Im nto sure if it can work or not but ill paste my ocde below and please have a look.

PS: please dont be harsh im new ahahah lol

[php]<?php
// Database Details
function db_CONNECT(){
$s_dbhost = ‘localhost’; $s_dbuser = ‘root’; $s_dbpass = ‘’; $s_dbname = ‘syst3m’;
$conn = mysql_connect($s_dbhost, $s_dbuser, $s_dbpass) or die (‘MYSQL CONNECTION ERROR’);
mysql_select_db($s_dbname);
}

// Connect
db_CONNECT();

function _get($sTABLE,$sVAR){

// Load DB Framework
function _getDB($sDBquery,$sDBtable,$sDBorder){
$load_DBquery = mysql_query("SELECT ".$sDBquery." FROM ".$sDBtable." ORDER BY ".$sDBorder."");
$get_DBresult = mysql_fetch_assoc($load_DBquery);
echo $get_DBresult[$sVAR];
	if(!$get_DBresult){
	die("<b>syst3m ERROR:</b> _getDB ERROR | Line 18");
}	

}

// Get Setting Data
if($sTABLE == 'setting'){ _getDB('*','s_settings','s_id');
	echo $get_DBresult[$sVAR];
}

// Get User Data
if($sTABLE == 'user'){ _getDB('*','s_user','u_id'); _getDB('*','s_user_level','ul_id'); _getDB('*','s_user_settings','us_id');
	echo $get_DBresult[$sVAR];
}

// Get Page Data
if($sTABLE == 'page'){ _getDB('*','s_page','p_id'); _getDB('*','s_page_settings','ps_id');
	echo $get_DBresult[$sVAR];
}

// Get News Data
if($sTABLE == 'news'){ _getDB('*','s_news','n_id'); _getDB('*','s_news_settings','ns_id');
	echo $get_DBresult[$sVAR];
}

};

//test above eg:
$site_name = _get(‘setting’,‘s_site_name’); // this wont send s_site_name to $sVAR s_site_name is the db table name in the db
echo $site_name;

?>[/php]

When i run above code is get error: Notice: Undefined variable: sVAR in blah/blah/blah.php on line blah

:frowning: what can i do

What you have looks more like a class. All its telling you is that php sees the variable before its being occupied by something. Not really considered something to worry about. as for transferring them between functions, you either need to declare it in the () or make the variable global.

i have tryed to make the var global but it still wont register in the mysql query, should this be a class instead? basically it will make it easy to access db info via a function eg: _get(‘setting’,‘page_title_data’); will lookup setting tabke in database and get the page_title_data value and echo it

I can’t think of any reason to ever use a nested function in PHP. If you wanted this to work, your only option would be to pass $sVAR to _getDB() function.

You should certainly be using an object here.

Sponsor our Newsletter | Privacy Policy | Terms of Service