Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Insert if this ip dont have any records

Tags:

sql

php

mysql

I use:

INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
        '{$_SERVER['REMOTE_ADDR']}');";

I would like to add an if condition in the IF statement so that.

IF SELECT ip from rating 
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name 
then update ELSE INSERT new row

is it doable or I better code it in php ? thank you very much

P.s: I know how to do it with php, I want to learn it with MySQL.

Also i require that all 3 name,section,ip matchs not only ip

like image 417
Zalaboza Avatar asked Dec 10 '25 09:12

Zalaboza


1 Answers

Assuming you have a unique constraint (UNIQUE index or PRIMARY KEY) on ip, section and name, you can use this syntax:

INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section', '{$_SERVER['REMOTE_ADDR']}')
ON DUPLICATE KEY UPDATE user = VALUES(user), rating = VALUES(rating);
like image 196
Eric Petroelje Avatar answered Dec 12 '25 22:12

Eric Petroelje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!