How to show MySQL errors from a failed Modx / xPDO query object?

How to show mysql throws error when trying to insert data into user table and insert failed?

For example, below is the bit of code that should (will) fail with an SQL error.

$insert = "some insert sql statement that will fail";

$myquery = $modx->query($insert);

    if(!$myquery){

        echo 'error occurred! <br>';

    }

      

How to get back what was actually a mistake [i.e. column mismatch, unique id exists, etc.]?

+3


source to share


2 answers


Based on examples from the xPDO Getting Started Guide , $modx

in this context is a class that extends PDO

, and the result resource object is $myquery

most likely an object PDOStatement

.

Thus, you can set the exception error mode to $modx

, as you would with a normal PDO object.

$modx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      

to make it throw errors on failure. By default, PDO errors are silent; its error methods are described here .

Bugfix: Looking into the xPDO source , it does not extend PDO

, but contains PDO

both a property and implement PDO methods by passing them to the connection property. So the call setAttribute()

will be passed to the underlying object PDO

and should work accordingly.

The xPDO constructor greatly extends the functionality from the regular PDO constructor and takes an array of parameters in the 5th parameter where you can set the mode error rather than set it later via setAttribute()

:



$xpdo = new xPDO($dsn, $user, $password, [], [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);

      

Whichever method you choose, you can wrap your code in a block try/catch

to catch type exceptions PDOException

on error:

    try {
      $insert = "some insert sql statement that will fail";
      $myquery = $modx->query($insert);
   }
    catch (PDOException $e) {
      echo 'error occurred! ' . $e->getMessage() . '<br>';
    }

      

You can also just set errormode to a value PDO::ERRMODE_WARNING

, and PHP will instead generate messages E_WARNING

that, unlike exceptions, are not fatal.

I was able to test all of this work as expected by installing a quick test using xPDO.

+2


source


There is a slightly easier way to track your custom xpdo request.

$c = $modx->newQuery('modResource');
$c->where(array(
    'id1' => 1
));

// print request for control
print_r($c->toSQL());

$s = $c->prepare();
$s->execute();

print_r($s->errorInfo());

      

After execution, we can catch the error:



Array ( [0] => 42S22 [1] => 1054 [2] => Unknown column 'modResource.id1' in 'where clause' )

      

This is because xpdo uses pdo and manages execution with it. Some code from xpdo source:

/**
 * @see http://php.net/manual/en/function.pdo-errorinfo.php
 */
public function errorInfo() {
    if (!$this->connect()) {
        return false;
    }
    return $this->pdo->errorInfo();
}

      

+2


source







All Articles