How do I check the result of a Fat Free Mapper call to save a DB record?

1.2k views Asked by At

I'm using the SQL Mapper to update records in my MYSQL DB which is working ok - but I can't see how to check what the outcome of the update was from the call to save() or update().

Update seems to return the entire mapper object which doesn't offer an obvious way of checking if the update failed. Should I be checking the return code or catching an exception?

Any help appreciated!

Matt

3

There are 3 answers

0
xfra35 On BEST ANSWER

libregeek is right, you should enable PDO exceptions and catch them:

$db=new \DB\SQL($dsn,$user,$pwd,[
  \PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION]
);

$mytable=new \DB\SQL\Mapper($db,'mytable');

try {

  $mytable->copyfrom($input);
  $mytable->save();
  echo 'Data successfully saved';

} catch(\PDOException $e) {

  echo 'Something went wrong';
  // let's find what exactly:
  $err=$e->errorInfo;
  echo $err[0];// PDO error code
  echo $err[2];// driver specific error message

}

See also this topic.

0
Njuguna Mureithi On

All mappers extend Cursor. The problem is cursor methods save() and update() return this.

Related: see this issue on Github: https://github.com/ikkez/f3-cortex/issues/3

The way out may be to use hooks such as aftersave or beforesave:

$mapper->aftersave(function($self,$pkeys){
  //do something after inserting or updating
  // Maybe validate
});

Hope this helps.

0
libregeek On

You could get PDO style exceptions if you enable it while initializing the DB object.

Refer https://fatfreeframework.com/3.6/sql

PDO Exception reference: http://php.net/manual/en/class.pdoexception.php

P.S: I haven't tried them, so not sure how much they are useful.