Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

pdo

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 same as already present in the database. I know that rowCount() in such a case returns 0.
  2. the row I'm 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 by a SELECT statement, to figure out if the record I'm trying to update does in fact exist? Or is there another common practice for this sort of thing.

I've been perusing through the documentation, but cannot find a conclusive answer: http://php.net/manual/en/pdostatement.rowcount.php

I've come across this StackOverflow answer, that suggests that rowCount() might return NULL in some scenario's, but I don't think it's apliccable to my scenario: see Why does PDO rowCount() return 0 after UPDATE a table without modifying the existing data?

From the comments in this question:

If the data hasn't been modified, the rowCount will be zero. If the data was modified, the rowCount will be one or higher. If there was an error, rowCount will be null or false or something non-zero.

UPDATE I've found another question that gives an example of the proposition in the comments below: Getting the insert and update ID with PDO

UPDATE2 Another question proposes another solution, via PDO::MYSQL_ATTR_FOUND_ROWS PDO - check if row was updated?

like image 821
chocolata Avatar asked Jul 06 '13 10:07

chocolata


1 Answers

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

like image 82
DTecMeister Avatar answered Nov 11 '22 16:11

DTecMeister