Lee Posted January 18, 2011 Share Posted January 18, 2011 Can I use a variable inside an sql query to determine which table to select from? The 2 functions below do exactly the same thing, they're just selecting data from different tables. I'm not sure how I can do it. Maybe put a parameter in the function & use sprinf? // Output the page data function showpages() { db_connect(); $query = ("SELECT * FROM pages"); // can I change pages to a variable somehow? $result = mysql_query($query); $result = result_to_assoc($result); return $result; } // Echo the pricelist data into the pricelist form function show_pricelist() { db_connect(); $query = ("SELECT * FROM pricelist"); // Again, if pricelist can be a variable, then I need only 1 function $result = mysql_query($query); $result = result_to_assoc($result); return $result; } Quote Link to comment https://forums.phpfreaks.com/topic/224825-variables-in-sql-query/ Share on other sites More sharing options...
bh Posted January 18, 2011 Share Posted January 18, 2011 function show_pricelist($table) { db_connect(); $query = ("SELECT * FROM {$table}"); // Again, if pricelist can be a variable, then I need only 1 function $result = mysql_query($query); $result = result_to_assoc($result); return $result; } Quote Link to comment https://forums.phpfreaks.com/topic/224825-variables-in-sql-query/#findComment-1161279 Share on other sites More sharing options...
dragon_sa Posted January 18, 2011 Share Posted January 18, 2011 sure can set the variable $pages and change pages to $pages in your query same with pricelist Quote Link to comment https://forums.phpfreaks.com/topic/224825-variables-in-sql-query/#findComment-1161281 Share on other sites More sharing options...
mrqpro Posted January 18, 2011 Share Posted January 18, 2011 Sure. You can set the variable in your sql query like this : $sql = "SELECT * FROM {$tablename};"; http://dacloi.com Quote Link to comment https://forums.phpfreaks.com/topic/224825-variables-in-sql-query/#findComment-1161282 Share on other sites More sharing options...
Lee Posted January 18, 2011 Author Share Posted January 18, 2011 Thank you Quote Link to comment https://forums.phpfreaks.com/topic/224825-variables-in-sql-query/#findComment-1161284 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.