Pregunta

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.

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.

this is my update statement

UPDATE surveys_answers_controller                                                           
SET controller_id = $field['answer']
WHERE group_id = $group_id AND question_id = $field['question_id']

note that neither group_id nor question_id are a primary key in this table but a foreign keys.

I tried to use $db->lastInsertId() but it is always returning 1 wether it update a record or not. I am not sure why!

this is what I tried

$update_answer = $db->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->lastInsertId();
if(empty($last_id)){
$update_answer = $db->processQuery('INSERT INTO surveys_answers_controller( controller_id, group_id, question_id)VALUES(?,?,?)',
array($field['answer'], $group_id, $field['question_id']) );        
}

$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.

I am using PDO to connect to the database not mysqli.

How can I write a query that check for existing record and it update it if exists otherwise it inserts it?

Thanks

¿Fue útil?

Solución

Use PDOStatement::rowCount() instead of $db->lastInsertId. This finds the number of rows affected by the last update/insert/delete. If zero then do the insert.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top