1

I'm building an web application where the user fills an html form and the information captured is used to create a table with corresponding columns. However, mysql returns an error where the POST variable is used to name the columns. Here is a sample of the code:

$questionnaire = mysql_real_escape_string(htmlentities($_POST['questionnaire']));
$question = mysql_real_escape_string(htmlentities($_POST['question']));
$answer1 = mysql_real_escape_string(htmlentities($_POST['answer1']));
$answer2 = mysql_real_escape_string(htmlentities($_POST['answer2']));

mysql_query = "CREATE TABLE $questionnaire
               (id int(5) NOT NULL AUTO INCREMENT,
                PRIMARY KEY(id),
                question varchar(200),
                '$answer1' varchar(200),
                '$answer2' varchar(200) )";

How do I make the value in $answer1 be used to give a column its name?

Jordan Carroll
  • 696
  • 2
  • 11
  • 29

3 Answers3

0

use BACKTICK not SINGLE QUOTES as column names are identifiers,

mysql_query = "CREATE TABLE $questionnaire
               (id int(5) NOT NULL AUTO INCREMENT,
                PRIMARY KEY(id),
                question varchar(200),
                `$answer1` varchar(200),
                `$answer2` varchar(200) )";
Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

Don't put it in parentheses ('). If you escape column names, you will need to use backticks.

However, you should reconsider your table layout. If you have to generate tables and/or columns on the fly, there is most certainly something wrong with your design.

mrks
  • 8,033
  • 1
  • 33
  • 62
  • the number of columns is fixed but the names vary from table to table. its a questionnaire so i thought of allocating a table to each question and its answers. – user2262552 Apr 09 '13 at 16:30
0

change this AUTO INCREMENT to AUTO_INCREMENT

http://www.w3schools.com/sql/sql_autoincrement.asp

echo_Me
  • 37,078
  • 5
  • 58
  • 78