Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if UPDATE or INSERT when using ON DUPLICATE KEY [duplicate]

Tags:

php

mysql

mysqli

I'm using a mysqli/php query that looks like this:

$query = "
INSERT INTO table (unique_key, column_1, column_2) 
VALUES (?,?,?)
ON DUPLICATE KEY UPDATE
value_1 = ?, value_2 = ?";
if ($statement = $mysqli->prepare($query))
{
    $statement->bind_param("iiiii", $unique_key, $value_1, $value_2, $value_1, $value_2);
    $statement->execute();
    $statement->close();
}

How do I tell if the query executed an UPDATE or an INSERT?

like image 794
Amy Neville Avatar asked Dec 06 '22 17:12

Amy Neville


1 Answers

You can use mysqli_affected_rows and check return value. From MySQL docs:

For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values.

like image 53
revo Avatar answered Dec 09 '22 16:12

revo