0

How do I execute a SQL query with a variable as table? I have a dropdown menu in HTML and want the chosen option to be the table name. But as I now query

$klas = $_POST['klasDown'];
 $query = 'INSERT INTO $klas 

gives me the error message:

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Table 'izandb.$klas' doesn't exist'

EDIT: Why has this been closed that quickly? I dont really is the same question as is being said to be a duplicate of

Y_Lakdime
  • 793
  • 2
  • 11
  • 27
  • Dont use single quotes. Also use a whitelist before putting `$klas` into the query. – chris85 Aug 25 '17 at 23:22
  • When a variable is in single quotes it is not a variable it is the literal value. Please post questions as comments here. You can read more with the links at the top of the question, or on the manual page, http://php.net/manual/en/language.types.string.php.`Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.`. – chris85 Aug 25 '17 at 23:50
  • @chris85 so what should I use in this case? (Using the _POST value from html option tag? – Y_Lakdime Aug 25 '17 at 23:52
  • Double quotes, or concatenate. `$query = "INSERT INTO $klas "` or `$query = 'INSERT INTO ' . $klas . ' rest of query';` – chris85 Aug 26 '17 at 00:06

0 Answers0