I need to update a record in the database, but I don't know if that record already exists. If it exists, update it, else insert it. Now I came up with this code:
1: <?php
2: $query = "UPDATE user_meta SET active = '0' WHERE user_id = '125'";
3: $mysqli->query($query);
4:
5: if($mysqli->affected_rows == 0){
6: $query = "INSERT INTO user_meta (user_id, active) VALUES ('125', 0)";
7: $mysqli->query($query);
8: }
The table:
CREATE TABLE `user_meta` (
`user_id` int(11) DEFAULT NULL,
`active` tinyint(4) DEFAULT NULL,
UNIQUE KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This code is working fine for me, but it actually generates an error which I neglect.
The problem is in this line 5
. The affected_rows is 0
if nothing is changed, even if the record already exists. But this will trigger the INSERT statement. This one fails because the user_id field is unique, now I'm ignoring this so my code is working fine.
But is this the way to go? Or should I do first a select and than update or insert?