I have a table which looks f.ex. like this:
id (primaryKey, auto_increment) | fruit | color
I would like to insert values for fruit and color, if the fruit value does not exist, else I would like to update just the color and get back the id of the inserted or updated row.
F.ex. if I have a row with:
1234 | apple | red
and want to update the color of the apple to green, without knowing that there is already a row containing an apple. I use this code:
$sqli = get_db();
$q1 = "INSERT INTO table (fruit, color) VALUES ('apple', 'green') ON DUPLICATE KEY UPDATE color='green', id=LAST_INSERT_ID(id)";
$r1 = $sqli->query($q1);
$insertedOrUpdatedID = $sqli->insert_id();
I want to update the existing row to:
1234 | apple | green
and get back the id (1234) in $insertedOrUpdatedID.
I think I need to tag the fruit column in any way. When I'm executing this code, it always creates a new row (1235|apple|green) without updating the existing one or returning the edited id.
SOLUTION:
Changing the type of 'fruit' from text to varchar(100) and setting its KEY to UNIQUE solves the problem. Moreover change the last line of the code to:
$insertedOrUpdatedID = mysqli_insert_id( $sqli );
in order to get the right ID.
Happy coding!
UNIQUEconstraint tofruitattribute may prevent inserting duplicate rows.