MySQL Update If Exist Else Insert Procedure

April 22, 2016

Are you tired of checking data in your code before inserting? Well MySQL procedures are here to rescue. This simple procedure shows how you can do that:

<br /> CREATE PROCEDURE `update_insert_user`( IN uid2 int )<br /> BEGIN<br /> DECLARE last_login2 DATETIME;<br /> SELECT `last_login` INTO last_login2 FROM `user` WHERE `uid` = uid2 LIMIT 1;<br /> IF last_login2 IS NULL THEN<br /> INSERT INTO `user` (`uid`,`last_login`) values (uid2, now());<br /> ELSE<br /> UPDATE `user` SET `last_login` = now() WHERE `uid` = uid2 LIMIT 1;<br /> END IF;<br /> END<br />

You just call one line of SQL from your code, keeping your code cleaner and easier to debug.

© 2017 Amer Khalid