user3271847
user3271847

Reputation: 35

Adding column to table returns error saying error in SQL syntax

When I run this code:

$addUniverseColumn = $db->prepare("ALTER TABLE spaceships ADD :universe int");
$addUniverseColumn->bindParam(":universe", $name);
$addUniverseColumn->execute();

I get the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''asfa' int' at line 1' in D:\XAMPP\htdocs\php\locationconfig.php:63 Stack trace: #0 D:\XAMPP\htdocs\php\locationconfig.php(63): PDOStatement->execute() #1 {main} thrown in D:\XAMPP\htdocs\php\locationconfig.php on line 63

Note: $addUniverseColumn->execute(); is the line 63.

I have little to no idea as to what the problem is. I've searched for an answer to the problem but I can't find anything. Any help would be appreciated. :)

Upvotes: 0

Views: 98

Answers (1)

Marc B
Marc B

Reputation: 360682

Placeholders can only work for VALUES, never field/table names. You cannot use a placeholder for the field name in an ALTER query. You'll have to use good old string interpolation for it:

$db->prepare("ALTER TABLE spaceships ADD $name int");

Upvotes: 1

Related Questions