title: How to detect if a record has been modified in MySQL and php
body: <p>I am coding an application using php/MySQL. I got to a scenario where I need to update a record if it exists but if it does not exist then insert a new record.</p>
  
  <p>Please note that I can NOT add unique indexes so I can not use REPLACE or INSERT INTO... ON DUPLICATE KEY UPDATE. also I don't know the primary key for the record that I am trying to update.</p>
  
  <p>this is my update statement</p>
  
  <pre><code>UPDATE surveys_answers_controller                                                           
  SET controller_id = $field['answer']
  WHERE group_id = $group_id AND question_id = $field['question_id']
  </code></pre>
  
  <p>note that neither group_id nor question_id are a primary key in this table but a foreign keys.</p>
  
  <p>I tried to use $db->lastInsertId() but it is always returning 1 wether it update a record or not. I am not sure why!</p>
  
  <p>this is what I tried</p>
  
  <pre><code>$update_answer = $db-&gt;processQuery('UPDATE surveys_answers_controller
  SET controller_id = ?
  WHERE group_id = ? AND question_id = ? ',
  array($field['answer'], $group_id, $field['question_id']) );
  
  $last_id = $db-&gt;lastInsertId();
  if(empty($last_id)){
  $update_answer = $db-&gt;processQuery('INSERT INTO surveys_answers_controller( controller_id, group_id, question_id)VALUES(?,?,?)',
  array($field['answer'], $group_id, $field['question_id']) );        
  }
  </code></pre>
  
  <p>$last_id is always returning 1 for some reason whether it did modify a record or not and that is why the insert statement is ignored.</p>
  
  <p>I am using PDO to connect to the database not mysqli.</p>
  
  <p>How can I write a query that check for existing record and it update it if exists otherwise it inserts it?</p>
  
  <p>Thanks</p>