Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql update query, what if value didn't change? how do I check for that?

Tags:

php

mysql

When executing UPDATE statement, if value is same as new value than rowCount doesn't change. But for purposes of my application this is also a success. So how do I check for successful update no matter if value changed or not?

$stmt = $conn->prepare('UPDATE users SET name = :name WHERE id = :id');

$result = $stmt->rowCount(); // 1

if ($result == 1) {echo "success!";}
like image 240
Red Balloon Avatar asked Nov 08 '13 11:11

Red Balloon


People also ask

How do I know if MySQL update query was successful?

Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.

What happens if you update a record that doesn't exist SQL?

Update won't insert records if they don't exist, it will only update existing records in the table.

Which is the correct syntax of update query in MySQL?

MySQL Update Command Syntax The basic syntax of the Update query in MySQL is as shown below. UPDATE `table_name` is the command that tells MySQL to update the data in a table . SET `column_name` = `new_value' are the names and values of the fields to be affected by the update query.


2 Answers

You're not executing the query, merely preparing it. So rowCount() will report an invalid number of rows (the one referring to the last executed query), since no rows were affected yet, and the system doesn't know beforehand how many will be, once you execute the prepared statement with specific param values.

You should check for success upon executing the statement. The execute() method will return true if it succeeds and false otherwise. So if execution success is the only thing you need, then you should do it along the lines of:

$stmt = $conn->prepare('UPDATE users SET name = :name WHERE id = :id');

$result = $stmt->execute($params); // <-- execute first!

if ($result) {echo "success!";}
like image 111
geomagas Avatar answered Oct 02 '22 10:10

geomagas


I agree with Legionar. But instead of count I used to add a column that contains the last update time. So that I can use that to get the entries that got updated after a specific time. In this way I able to reduce the number of entries send to client. The final decision is based on your requirement.

$stmt = $conn->prepare('UPDATE users SET name = :name, updateTime = currentTime WHERE id = :id');   
$result = $stmt->rowCount(); // 1
if ($result == 1) {echo "success!";}
like image 43
Damodaran Avatar answered Oct 02 '22 09:10

Damodaran