1

I'm trying to create a statement that inserts and updates rows in my database which changes a value in my database when values has changed while updating the row.

I'm not sure if my question is clear enough but here is my code (check the comments, this should clear things up):

$stmProducts = $db->prepare("
     INSERT INTO
          products
     SET
          identifier      = :identifier,
          title           = :title,
          price           = :price,
          content         = :content
     ON DUPLICATE KEY UPDATE
          title           = :title,
          price           = :price,
          content         = :content
          // If any values (title, price or content) has been changed while updating:
          // updated      = true
");

I've tried something with CASE WHEN but that didn't work, I don't have the exact code I used but it was something like this:

updated = CASE WHEN title != :title THEN true END 

I could be looking into the completely wrong direction but what's the best way to get to what I'm trying to achieve?

1 Answer 1

1

You can know it examining PDOStatement::rowCount(). With an insert it will return 1, while with an update will return 2.

Check the documentation

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, and 2 if an existing row is updated.

Sign up to request clarification or add additional context in comments.

2 Comments

they're using PDO, and not MySQLi
@AlbertoFernández I just tested it and it seems to work great, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.