How can I change store procedure codes to pure sql code

How can I change this store procedure to pure mysql code. It may also be in PHP
This is just an example of what I want to do. A rough sketch.
BEGIN
GetProduct (int pid){
‘DECLARE productQuantity;’
‘SELECT * FROM product WHERE id = pid INTO productQuantity’
}
END;

That SP selects all fields of the product table for a single product by id and can be done in pure SQL as follows.

SELECT * FROM product WHERE id = ?

THis is the actual code

-- 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$

and this is the code I change it to

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;
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.