如何将此存储过程mysql代码更改为纯mysql代码

时间:2019-01-03 08:16:55

标签: php mysql sql

我想将此存储过程代码更改为纯mysql代码,我这样做了,但是它抱怨DECLARE productQuantity INT并说该变量未设置或存在

我试图通过从纯代码中删除存储过程代码(函数)来改变代码以达到我的理解

-- Create shopping_cart_add_product stored procedure
CREATE PROCEDURE shopping_cart_add_product(IN inCartId CHAR(32),
IN inProductId INT, IN inAttributes VARCHAR(1000))
BEGIN
    DECLARE productQuantity INT;
    -- Obtain current shopping cart quantity for the product
    SELECT quantity
    FROM shopping_cart
    WHERE cart_id = inCartId
    AND product_id = inProductId
    AND attributes = inAttributes
    INTO productQuantity;

    IF productQuantity IS NULL THEN
        INSERT INTO shopping_cart(cart_id, product_id, attributes,
        quantity, added_on)
        VALUES (inCartId, inProductId, inAttributes, 1, NOW());
    ELSE
        UPDATE shopping_cart
        SET quantity = quantity + 1, buy_now = true
        WHERE cart_id = inCartId
        AND product_id = inProductId
        AND attributes = inAttributes;
    END IF;
END$$

这是我将其更改为的代码

public function addProductToCart($cart_id, $product_id, $attributes){
        $addProduct = 'DECLARE productQuantity INT ';
        $addProduct .= 'SELECT  * FROM `shopping_cart` WHERE cart_id = 
' . $cart_id . ' AND product_id = ' . $product_id;
    $addProduct .= ' AND attributes = ' . $attributes . ' INTO 
productQuantity ';
        $addProduct .= 'IF productQuantity IS NULL THEN INSERT INTO 
`shopping_cart`(';
    $addProduct .= 'cart_id, product_id, attributes, quantity, added_on) VALUES (';
    $addProduct .= $cart_id . ', ' . $product_id . ', ' . $attributes . ', 1 , 1 , NOW()';
    $addProduct .= ' ELSE UPDATE `shopping_cart` SET quantity = quantity + 1, buy_now = true WHERE cart_id = ' . $cart_id;
    $addProduct .= ' AND product_id = ' . $product_id . ' AND attributes = ' . $attributes;

    $parameters = ['cart_id' => $cart_id, 'product_id' => $product_id, 'attributes' => $attributes];

    $query = $this->query($addProduct, $parameters);
    return $query;
}

private function query($sql, $parameters = []) {
    $query = $this->pdo->prepare($sql);
    $query->execute($parameters);
    return $query;
}

这段代码是用PHP7编写的

我希望它可以插入或更新数据库表中受影响的行

0 个答案:

没有答案