Michael Rich
Michael Rich

Reputation: 301

MySQL: Updating a Field With The Same Value

I use the below method to update a field comment_confidence in my comment table.

public function update_comment_confidence($confidence_score)
{
    $this->db->update($this->_table, array('comment_confidence' => $confidence_score), array('comment_id' => self::$comment_id));

    if($this->db->affected_rows() < 1) throw new Exception('failed to update comment     confidence');

    return;
}

Here's the code that call the above method:

$this->db->trans_start();
$this->create_vote($vote);

try
{
    $total_votes = $this->read_comment_total_votes();
    $confidence_score = $this->ranking->confidence($total_votes['upvote'],$total_votes['downvote']);
    // SKIP UPDATING COMMENT CONFIDENCE IF ITS CONFIDENCE IS 0 AND THE CONFIDENCE_SCORE IS 0
    $this->article_comment_model->update_comment_confidence($confidence_score);
}
catch(Exception $e)
{
    // transaction is rolled back
    throw new Exception($e);
}

$this->db->trans_complete();

When update_comment_confidence() method is passed a value of 0 and the value in the database is already 0 then an exception will be thrown. And all tables will be rolled back. This is because there was no affected rows during the update. This is not the functionality I intend.

What can I do to prevent the exception being throw in the update_comment_confidence when the field contains the same value?

Upvotes: 0

Views: 68

Answers (1)

Serhat Akay
Serhat Akay

Reputation: 534

Well if i were you I would not throw an exception when affected rows < 1

if($this->db->affected_rows() < 1)

Throw an exception when there is an error.

Upvotes: 1

Related Questions