I want to get a script running, which creates a column in a table, if does not exist. I am using the script of user abahet from mysql ALTER TABLE if column not exists
My php code (inside of the db-class) looks like this:
$sql = '
SET @preparedStatement = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = "' . $this->t($table) . '"
AND table_schema = DATABASE()
AND column_name = "' . $column . '"
) > 0,
"SELECT 1;",
"ALTER TABLE ' . $this->t($table) . ' ADD ' . $column . ' ' . $params . ';"
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
';
//die($sql);
$this->db($sql,'utf8');
Once executed, it throws the following error:
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 'PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
' at line 12
SET @preparedStatement = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = "ddpos_2_user"
AND table_schema = DATABASE()
AND column_name = "id_signature"
) > 0,
"SELECT 1;",
"ALTER TABLE ddpos_2_user ADD id_signature mediumint(7) DEFAULT 0;"
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
But when I copy the query from the error message into phpmyadmin, or take the output directly from die($sql) into phpmyadmin, the procedure works fine without errors, and the column id_signature is created.
Why?