Due to some changes in the DB, I need to alter a table to add one column to it, but even though the function is running, the table isn’t altered.
Here’s the ALTER TABLE code that I’ve written
$sql = "ALTER TABLE " . $packagetable . " ADD COLUMN price decimal(14,2) NOT NULL AFTER description;";
dbDelta($sql);
I couldn’t find the syntax for ALTER TABLE with dbDelta anywhere online.
EDIT: After looking at the ALTER TABLE statement in gravity forms plugin, I have updated the statement in single line.
You’ve used the
dbDelta
function incorrectly.The whole point of that function is you pass in a table creation SQL command.
If the table doesn’t exist, it creates it.
If the table exists but doesn’t match, it’s modified until it matches. This includes adding and updating columns, indexes, and other aspects.
So what you want to do is run dbDelta, and provide it with your table creation sql, not table alteration sql.
See here for the Codex’ take on adding an upgrade/alteration to a table using
dbDelta
But it goes further! dbDelta is a picky function, you can’t just put any SQL statement in there, it has to be formatted appropriately
Here’s what the codex says on that same page:
And from another:
To add column to some WP table in DB, you could use
$wpdb
for it:$wpdb->query()
returns false if your query went wrong, according to method’s documentation. So you could write some if-else statement to do something on success or error:If you need add your new column after special column, just use
AFTER
in query:Also, you could change
or drop column
Small tip: In PHP, inside double-quote (
"
), you could use variable in curly brackets ("foo {$var} bar"
) or without them ("foo $var bar"
) to input variable to string, instead of concatenation ("foo " . $var . " bar"
). I use it in code above. Learn more about string parsing in php.