PDO does not paint errors

0

Good afternoon, I am trying to tell PDO that when a SQL statement error is generated, the error code is generated, and currently I think it is due to the connection:

public function __CONSTRUCT() {
    try {
        $this->pdo = new PDO('mysql:host=localhost;dbname=prueba;charset=UTF8', 'root', '');
        $this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
        $this->pdo->exec("SET NAMES 'utf8';");
    } catch (Exception $e) {
        die($e->getMessage());
    }
}

And for what I've seen I have to add a line like this

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Why should my code be left as follows?

public function __CONSTRUCT() {
    try {
        $this->pdo = new PDO('mysql:host=localhost;dbname=prueba;charset=UTF8', 'root', '');
        $this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $this->pdo->exec("SET NAMES 'utf8';");
    } catch (Exception $e) {
        echo 'Exception -> ';
        var_dump($e->getMessage());
    }
}

But I must have some error because it does not launch any kind of error.

One of the functions that I use for example is this

public function Registrar(Categoria $data) {
    try {
        $sql = "INSERT INTO categoria (acronimo,categoria,registro_calidad)
            VALUES (?, ?,?)";
//Ejecucion de la consulta siguiente
        $this->pdo->prepare($sql)->execute(array(
            $data->__GET('acronimo'),
            $data->__GET('categoria'),
            $data->__GET('registro_calidad')
                )
        );
    } catch (Exception $e) {
        die($e->getMessage());
    }
}

In brief summary, I want you to paint the SQL error you should throw. Thank you very much

    
asked by Alberto Cepero de Andrés 11.05.2017 в 13:53
source

1 answer

1

you should use PDOException instead of Exception

    
answered by 11.05.2017 / 15:33
source