How do I show the error mysql throws when I try to insert data into a custom table and the insert fails?
For example, below a 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 do I return what the error actually was [i.e. column mismatch, unique id exists etc.]?
Based on the examples in the xPDO Getting Started guide,
$modxin this context appears to be a class extendingPDOand the result resource object$myqueryis likely aPDOStatementobject.You can therefore set an exception error mode on
$modxas you would with a normal PDO object.to force it to throw errors on failure. By default, PDO errors silently; its error modes are documented here.
Correction: Looking into the xPDO source it does not extend
PDO, but rather contains aPDOobject as a property and implement PDO methods, passing them through to its connection property. So thesetAttribute()call will be passed through to the underlyingPDOobject and should work accordingly.The xPDO constructor extends functionality from a normal PDO constructor slightly, and accepts an array of options in the 5th parameter where you may set the error mode, rather than setting it later via
setAttribute():Whichever method you choose to set it, you may wrap your code in a
try/catchblock to catch exceptions of typePDOExceptionon error:You may also more simply set the errormode to
PDO::ERRMODE_WARNINGand PHP will instead just emitE_WARNINGmessages, which unlike exceptions, are non-fatal.I was able to verify all of this works as expected by setting up a quick test with xPDO.