Search code examples
phpmysqlpdoinnodb

Multiple Create Trigger query in PDO


I am trying to run the following SQL string in PDO. I can confirm that the code does execute in MySQL directly but running it in PHP PDO it throws an error.

I understand that the DELIMITER $$ is not available on the PDO interface. And according to how to execute mysql command DELIMITER it should be fine to just leave the delimiter out of the query.

QUERY STRING:

CREATE DEFINER=CURRENT_USER TRIGGER `M5_tblMVTransactionVat_VatInsert` AFTER INSERT ON `M2_tblVatRevisions`
FOR EACH ROW BEGIN
  UPDATE M5_tblMVTransactionVat
  SET M5_tblMVTransactionVat.vatID = 1;

END

CREATE DEFINER=CURRENT_USER TRIGGER `M5_tblMVTransactionVat_VatUpdate` AFTER UPDATE ON `M2_tblVatRevisions`
FOR EACH ROW BEGIN
  UPDATE M5_tblMVTransactionVat
  SET M5_tblMVTransactionVat.vatID = 2;

END

Run via either a simple PDO::exec or PDOStatement::prepare (with PDO::ATTR_EMULATE_PREPARES = 1) causes an error

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 'CREATE
DEFINER=CURRENT_USER TRIGGER `M5_tblMVTransactionVat_VatUpdate` AFTER
UPD' at line 8

I have confirmed that running only one Create Trigger at a time via PDO does not cause the same error and the trigger is created successfully. .

How do I execute multiple create trigger queries on a PDO connection?


Solution

  • Don't execute multiple statements at a time.

    There is no reason to do so, and it causes problems if you try.

    The former Director of Engineering for MySQL once told me, there is no reason for multi_query to exist, it can only do harm (that's my paraphrasing).

    It's simpler and safer to execute each CREATE TRIGGER statement in its own call to PDO::exec().