0

I am trying to add a column in teacher table the name of the column is given by text field the code is here

$name=  cleanString($_POST['prog']);
$query_1="alter table teacher add '$name' varchar(40) null";
if (!mysql_query($query_1, $link)){
    echo mysql_error();
}

but it gives the error like "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''students' varchar(40) null' at line 1"

but when I use the query $query_1="alter table program_course add 'students' varchar(40) null";

this query works fine and there is no error any body who can help me about it please

  • 3
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also likely to be **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** (a function called `cleanString` sounds generic enough that it is likely to have problems)) that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Feb 07 '14 at 11:40
  • 3
    Don't add courses in the teacher table. Create a course table and give it a teach column. – Quentin Feb 07 '14 at 11:41
  • You sure that query runs fine exactly as it does? I didn't think the column would add with it being a string? Try removing the single quotes around the var? – d1ll1nger Feb 07 '14 at 11:43
  • may be you are not connected with mysql(principal) – Dinesh Feb 07 '14 at 11:44
  • dear this is not the problem I have used the same function for my other quries also but the problem is only with this query if a hard code the name of the column then there is no problem when i put the variable name in the query then it gives the error – Muhammad Aneeq Feb 07 '14 at 11:45
  • I am connected with mysql it is sure and I have tried by removing single quotes around the var but it gives error it only does not gives error when i use hard coded name for column – Muhammad Aneeq Feb 07 '14 at 11:48

1 Answers1

0

Try:

$query_1="alter table teacher add `$name` varchar(40) null";

Instead of :

$query_1="alter table teacher add '$name' varchar(40) null";

You were using invalid characters. You need ` instead of '

Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46