tags:

views:

99

answers:

3

For some reason I can't pass a var inside a mysql statement. I have a function that can be used for multiple tables. So instead of repeating the code I want to change the table that is selected from like so,

function show_all_records($table_name) {

     mysql_query("SELECT * FROM $table_name");

etc, etc...

}

And to call the function I use show_all_records("some_table") or show_all_records("some_other_table")

depending on which table I want to select from at the moment. But it's not working, is this because variables can't be passed through mysql statements?

+3  A: 

The code you pasted must work. The possible reasons it doesn't are:

  • You are using 'SELECT * FROM $table_name' (single quotes instead of double quotes)
  • You misspelled $table_name

Try die("SELECT * FROM $table_name"); and you'll see exactly what's wrong!

Andreas Bonini
+2  A: 

Try

$results = mysql_query("SELECT * FROM $table_name") or die(mysql_error());

and tell us what does it says. In theory $table_name should be parsed as a string, as it is inside "" and not ''

Ben
A: 

Your query looks fine. Can't see why that wouldn't work. Have you connected to the DB properly with mysql_connect() elsewhere in your code? Did the connection get established? Does the user you're connecting as have SELECT permissions on the table you're trying to access?

Marc B