Doctrine Error Handling (DBAL) for multiple queries

I have a schema sql file (with syntax error) including several queries for the settings database

example.sql

CREATE TABLE IF NOT EXISTS `example` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; CREATExxxxxxxxxx TABLE IF NOT EXISTS `example2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 

example.php

 $sqlContent = file_get_contents("example.sql"); $stmt = $conn->prepare($sqlContent); $result = $stmt->execute(); 

The execute method throws no exceptions, even if my sql is incorrect. it reports that it returns false on error, but returns true .

How do I do exception handling? How to check if my request has an error message?

+5
source share
1 answer

The problem is not in Doalrine DBAL, but in PDO. If you change the driver to mysqli (instead of pdo_mysql ), you will receive an error message of the following form:

[Teaching \ DBAL \ Exception \ SyntaxErrorException]
An exception occurred while executing "CREATE TABLE IF EXISTING example (

 `id` int(11) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 

AUTO_INCREMENT = 1;
CREATExxxxxxxxxx TABLE IF EXISTING example2 (

 `id` int(11) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 

AUTO_INCREMENT = 1; ':
You have an error in the SQL syntax; check the manual that matches your version of MySQL server for the correct syntax to use near 'CREATExxxxxxxxxx TABLE IF EXISTING example2 (
id int (11) NOT NULL AUTO_I 'on line 8

If you use PDO directly (not through Doctrine), then you will not receive an error message.

If you want it to work correctly, you must disable emulation of prepared statements (set PDO::ATTR_EMULATE_PREPARES to 0).

0
source

Source: https://habr.com/ru/post/1240527/


All Articles