JuanSedano
JuanSedano

Reputation: 1025

What is the best way to validate if a record was inserted successfully?

What is the best way to validate if a record was inserted successfully?

I'm using PDO Statements.

This:

/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
    include ("./businesslogic/dbconnection/cfg.php");
    try {
        $db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
        $sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
        $sql->bindParam(':filename',$filename);
        $sql->bindParam(':userid',$userid);
        $sql->execute();
        $sqlresult = $sql->rowCount();
        $db = null;
        return $sqlresult; //Then validate if result is greater than 0.
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    }
}

or this:

/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
    include ("./businesslogic/dbconnection/cfg.php");
    try {
        $db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
        $sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
        $sql->bindParam(':filename',$filename);
        $sql->bindParam(':userid',$userid);
        if ($sql->execute()) {
            $db = null;
            return TRUE; 
        } else {
            $db = null;
            return FALSE;
        } //Then validate if result is TRUE or FALSE.
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    }
}

Both ways works fine but im not sure what is the best, can you please help me?

Upvotes: 0

Views: 67

Answers (1)

deceze
deceze

Reputation: 522042

  1. PDO won't actually throw exceptions unless you tell it to. So your try..catch is entirely superfluous and will never do anything.
  2. If the statement was executed without error, that means the data was inserted/updated successfully. No need to count rows, unless you are interested in the specific details of how many rows were altered (which is a different topic than "is the data in my database now?").

Given this, I'd recommend to set PDO to throw exceptions in case of errors and not do any further explicit checking:

$db = new PDO("mysql:host=$server;dbname=$db", $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = $db->prepare('UPDATE users SET userpicture = :filename WHERE userid = :userid');
$sql->bindParam(':filename', $filename);
$sql->bindParam(':userid', $userid);
$sql->execute();

This may still mean that the statement did nothing if the user id didn't exist. This would point to a deeper bug in your app, it's questionable if the PDO code should care about it specifically.

Upvotes: 2

Related Questions