Can PDO rowCount() after UPDATE query show difference between “no changes made” and “unexisting row”?

后端 未结 2 1249
梦如初夏
梦如初夏 2021-01-12 16:40

I\'m doing an update query with PDO. I would like to figure out if my update query did not change anything in the database, since:

  1. the passed values are the sa
相关标签:
2条回答
  • 2021-01-12 17:05

    You could add conditionals to your 'where' clause so such as " and ColumnToUpdate <> 'NewValue'"

    0 讨论(0)
  • 2021-01-12 17:15

    I've solved it using the suggestions of @hjpotter92.

    // UID is the unique ID of my table, autoincremented etc...
    // Firstly, let's try to update my row
    $query = 'UPDATE my_table SET x=0, y=1, uid=LAST_INSERT_ID(uid) WHERE z=2';
    $sth = $dbh->prepare($query);
    if($sth->execute()) {
        if($dbh->lastInsertId() == 0) { // Record was not found, so insert it.
            $query = 'INSERT INTO my_table (x,y) VALUES (0,1)';
            $sth = $dbh->prepare($query);
            $sth->execute();
            if($sth->rowCount() > 0) {
                echo $dbh->lastInsertId(); // Return the UID of the inserted row
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题