How do I tell when a MySQL UPDATE was successful versus actually updated data?
Example:
TABLE id city_name 1 Union 2 Marthasville
If I run the following:
$data = array('city_name', 'Marthasville'); //update record 2 from Marthasville to the same thing, Marthasville. $this->db->where('id', 2); $this->db->update('table', $data); if($this->db->affected_rows() > 0) { //I need it to return TRUE when the MySQL was successful even if nothing was actually updated. return TRUE; }else{ return FALSE; }
This will return TRUE
every time the UPDATE statement is successful, but FALSE when no rows were actually updated.
I need it to return TRUE
every time the UPDATE statement was successfully executed even if it doesn’t actually change any records.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Have a look at mysql_affected_rows()
It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.
php.net says:
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last
query failed.
You could use the following to achieve your desired results:
if($this->db->affected_rows() >= 0){ }
Method 2
Then you would use mysql_query:
SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
Simple like this:
$result = $this->db->update('table', $data); if($result) { //without error even no row updated } else { }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0