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,
$modx
in this context appears to be a class extendingPDO
and the result resource object$myquery
is likely aPDOStatement
object.You can therefore set an exception error mode on
$modx
as 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 aPDO
object as a property and implement PDO methods, passing them through to its connection property. So thesetAttribute()
call will be passed through to the underlyingPDO
object 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/catch
block to catch exceptions of typePDOException
on error:You may also more simply set the errormode to
PDO::ERRMODE_WARNING
and PHP will instead just emitE_WARNING
messages, 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.