Can a PDO rowCount () after an UPDATE query show the difference between "no changes" and "an impossible row"?

I am making an update request with PDO. I would like to find out if my update request in the database has changed, because:

  • the values ​​passed are the same as in the database. I know that rowCount() in this case returns 0 .
  • The row I am trying to update does not exist in the database. As far as I can see, rowCount() in such cases also returns 0 .

Am I forced to precede my UPDATE with a SELECT statement to find out if the record I'm trying to update really exists? Or there is another common practice for this kind of thing.

I was looking through the documentation but cannot find the final answer: http://php.net/manual/en/pdostatement.rowcount.php

I came across this StackOverflow answer, which suggests that rowCount () can return NULL in some scenarios, but I don't think this applies to my scenario: see Why does PDO rowCount () return 0 after an UPDATE table without changing existing data?

From the comments in this question:

If the data has not been changed, rowCount will be zero. If the data has been changed, rowCount will be one or more. If error, rowCount would be null or false or something non-zero.

UPDATE I found another question that gives an example sentence in the comments below: Getting insert and update id using PDO

UPDATE2 Another question offers a different solution, via PDO::MYSQL_ATTR_FOUND_ROWS PDO - check if the row is updated?

+6
source share
2 answers

I solved this using @ hjpotter92's suggestions.

 // UID is the unique ID of my table, autoincremented etc... // Firstly, let 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
source

You could add conditional conditions to your where clause, for example, and ColumnToUpdate <> "NewValue"

0
source

Source: https://habr.com/ru/post/948836/


All Articles