Dario
Dario

Reputation: 714

Correct syntax to insert if not exist or update if exist SQL

I need a push to get working a IF EXIST UPDATE else, INSERT, below is my function that update the database:

function _updatePrices($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $price          = $data[1];
    $attribute_id   = '76';
    $websiteId      = $data[2];
    $productId      = _getIdFromSku($sku);

    $sql = "INSERT INTO " . _getTableName('catalog_product_entity_decimal') . "
            (entity_type_id, attribute_id, store_id, entity_id, value)
            VALUES (4, ".$attribute_id.", ".$websiteId.", ".$productId.", ".$price.")
            ON DUPLICATE KEY UPDATE 
            value = (".$price.")";
            "WHERE attribute_id = ".$attribute_id."
            AND entity_id = ".$productId."
            AND store_id = ".$websiteId."
            ";
    $connection->query($sql);
}

How can i declare the values to be inserted ?

Upvotes: 0

Views: 139

Answers (2)

aaron-bond
aaron-bond

Reputation: 3341

You're looking for on duplicate key UPDATE

More info here: http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

The correct method is:

INSERT INTO `table` (`columns here`) VALUES ('values here')
    ON DUPLICATE KEY UPDATE `column`=VALUES(`column`), `col2`=VALUES(`col2`)...

Upvotes: 2

Related Questions