Syntax error with IF EXISTS UPDATE ELSE INSERT

前端 未结 3 525
说谎
说谎 2020-12-14 13:20

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
           


        
相关标签:
3条回答
  • 2020-12-14 13:42

    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.

    0 讨论(0)
  • 2020-12-14 13:45

    This should do the trick for you:

    insert into 
        licensing_active (title_1, time) 
        VALUES('$title_1', '$time') 
        on duplicate key 
            update set time='$time'
    

    This is assuming that title_1 is a unique column (enforced by the database) in your table.

    The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.

    0 讨论(0)
  • 2020-12-14 13:46

    The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

    Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

    0 讨论(0)
提交回复
热议问题