Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if SQL UPDATE changed value of column

Tags:

sql

php

mysql

pdo

I have a table with a text column called myTextColumn. I would like to do something in the PHP application only if an UPDATE changed the value. I am not using triggers. Is there a better way to do so other than the following? Thank you

function updateTable($data)
{
    $sql='SELECT id FROM myTable WHERE id=:id AND myTextColumn!=:myTextColumn';
    $stmt=db::db()->prepare($sql);
    $stmt->execute($data);
    if($stmt->fetchColumn()) {
        $sql='UPDATE myTable SET myTextColumn=? WHERE id=?';
        $stmt=db::db()->prepare($sql);
        $stmt->execute($data);
        return true;
    }
    else {return false;}
}

if(updateTable(array('id'=>123, 'myTextColumn'=>'Some text goes here')))
{
    echo('It Changed');
}
like image 202
user1032531 Avatar asked Nov 23 '25 13:11

user1032531


1 Answers

You can check the rowCount after your PDO call. It'll tell you the number of rows affected by your UPDATE.

$sql='UPDATE myTable SET myTextColumn=? WHERE id=?';
$stmt=db::db()->prepare($sql);
$stmt->execute($data);
if ( $stmt->rowCount() > 0 )
{ /* do stuff */ }
like image 84
K.A.F. Avatar answered Nov 26 '25 03:11

K.A.F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!