delphi123 Posted December 9, 2007 Share Posted December 9, 2007 I've got a php page which is including a config page at the top like this: include("includes/rating_config.php"); now in this config file I've put a variable declaring the table name ($table="table1" Now when I refer to it in the file within a function in the SQL query, it doesn't work, however when I put it inside the function like this: function getRating($id){ $table = "table1"; $sel = mysql_query("SELECT rating_num FROM $table WHERE rating_id = '$id'"); } It works perfectly!? Is there a way of making my variable work within functions? ?> Link to comment https://forums.phpfreaks.com/topic/80880-why-doesnt-this-work/ Share on other sites More sharing options...
themistral Posted December 9, 2007 Share Posted December 9, 2007 You could try adding the tablename to the function parameters function getRating($id, $tablename){ $sel = mysql_query("SELECT rating_num FROM $tablename WHERE rating_id = '$id'"); } Then when you call the function, use the variable from your include file. Link to comment https://forums.phpfreaks.com/topic/80880-why-doesnt-this-work/#findComment-410282 Share on other sites More sharing options...
p2grace Posted December 9, 2007 Share Posted December 9, 2007 You could also try adding "`" around the mysql fields. function getRating($id, $tablename){ $sel = mysql_query("SELECT `rating_num` FROM `$tablename` WHERE `rating_id` = '$id'"); } Link to comment https://forums.phpfreaks.com/topic/80880-why-doesnt-this-work/#findComment-410307 Share on other sites More sharing options...
revraz Posted December 9, 2007 Share Posted December 9, 2007 If you don't pass a variable to the function, it can't see it. Search for Variable Scope Link to comment https://forums.phpfreaks.com/topic/80880-why-doesnt-this-work/#findComment-410319 Share on other sites More sharing options...
spadmore Posted December 9, 2007 Share Posted December 9, 2007 This is a typical variable scope problem. That variable is not on the stack of that function by default and must be passed in by reference or by value. - Shelon Padmore Link to comment https://forums.phpfreaks.com/topic/80880-why-doesnt-this-work/#findComment-410334 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.