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?
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!
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 ''
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?
My recent experience with SQL, PHP, and MySQL showed me that I should write SQL statements like below to have them work, whether inside PHP scripts or from SQL interaction in phpMyAdmin. Otherwise my queries did not work. i just modify same code you have posted above to generalize a bit what i come up with. and give general rules that work.
beware single quotes around any value(record value not a db, table or column name) whether data representing itself or the variable name represent that data. i mean '
mark. also variable scopes in the language php should be regarded as always, that is another thing.
function show_all_records($table_name) {
mysql_query("SELECT `Username` FROM `$table_name` WHERE `Username` = 'edwin'");
etc, etc...
}
In SQL I discovered I should follow the following syntax rules to have my queries work in general:
- Double-quote all SQL query. i mean the
"
mark. - Backquote all database names and table names and column names(column names can be left non-quoted, as well). i mean the ` (option + comma on Macintosh).
- Single-Quote all values. i mean the
'
mark. - Quote the variables with the same quotation mark that would be done for their values regarding above three rules.
精彩评论