PHP MySQL,IF EXISTS更新ELSE插入,似乎不起作用

时间:2015-07-30 12:05:31

标签: php mysql mysqli mysqli-multi-query

我试图让这个代码更新,如果参数存在,但是,当我执行没有任何事情发生时(它确实说完了,更新产品,但更新products_description,似乎没有用。代码在这里:

    $query =   "UPDATE products 
            SET products_reference='$varenummer', products_price='$pris'
            WHERE products_id='$id';";

            for ($x = 1; $x <= $amountOfLanguages; $x++) {
                $varenavn = $_POST["varenavn-" . $x];
                $korttekst = $_POST["korttekst-" . $x];
                $langtekst = $_POST["langtekst-" . $x];

                $query .=  "IF EXISTS (SELECT * FROM products_description WHERE products_id='$id' AND languages_id='$x')
                                UPDATE products_description
                                SET products_description_name='$varenavn', products_description_short_description='$korttekst', products_description_description='$langtekst'
                                WHERE products_id='$id'
                                AND languages_id='$x'
                            ELSE
                                INSERT INTO products_description (products_id, languages_id, products_description_name, products_description_short_description, products_description_description)
                                VALUES ('$id', '$x', '$varenavn', '$korttekst', '$langtekst');";
            } 

            if ($conn->multi_query($query) === TRUE) {
                //header("Location: ./");
                //die();
                echo "done";
            } else {
                echo "Error: " . $query . "<br>" . $conn->error;
            }

我不能真正使用ON DUPLICATE,因为我不知道唯一的密钥,我只知道“products_id”和“languages_id”。

提前致谢。

1 个答案:

答案 0 :(得分:0)

你可以在mysql中使用更简洁,更紧凑的语法 - 在重复更新时使用&#39; - 对于这种情况。查询的一般原则如下: -

insert into `TABLE` ( `FIELD1`,`FIELD2`, `FIELD3` ) values ( 'VALUE1','VALUE2','VALUE3' )
on duplicate key
    update
        `FIELD1`='VALUE1',
        `FIELD2`='VALUE2',
        `FIELD1`='VALUE3';

Basing this on original query.
------------------------------

insert into `products_description` 
    (`products_id`, `languages_id`, `products_description_name`, `products_description_short_description`, `products_description_description` )
    values
    ( '$id', '$x', '$varenavn', '$korttekst', '$langtekst' )
    on duplicate key
    update
        `products_id`='$id',
        `languages_id`='$x';