Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error with IF EXISTS UPDATE ELSE INSERT

I'm using MySQL 5.1 hosted at my ISP. This is my query

mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
    BEGIN
        UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
    END ELSE BEGIN
        INSERT INTO licensing_active(title_1) VALUES('$title_1')
    END   
") or die(mysql_error());  

The error is

... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1

My actual task involves

WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...

but I have reduced it down to make things simpler for my problem solving

In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.

like image 612
Openstar63 Avatar asked Sep 15 '12 10:09

Openstar63


People also ask

Can we use insert in place of update?

No. Insert will only create a new row.

How do you insert into if not exists?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.


1 Answers

Here is a simple and easy solution, try it.

$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");

if( mysql_num_rows($result) > 0) {
    mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
    mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}

Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.

like image 190
Sohail Ahmed Avatar answered Oct 06 '22 01:10

Sohail Ahmed