问题
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?
回答1:
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()
.
回答2:
You want a bunch of initialization stuff in a file? Then why bother with PHP; do
mysql ... -e "source foo.sql"
Ok, you do want PHP to run things? Then do this from php:
execcute('mysql ... -e "source foo.sql"');
But, you had better button down the hatches -- this would be a wonderful way for a hacker to wreak havoc.
来源:https://stackoverflow.com/questions/50966979/multiple-create-trigger-query-in-pdo