代码不适用于Joomla modul - 购物车

时间:2014-01-28 20:41:01

标签: php session joomla joomla-extensions joomla3.0

我已经在php中构建了一个简单的购物车,作为独立版本,它可以正常工作。 现在我尝试将它作为Joomla模块运行。但是,当你现在调用此功能时,产品将首次添加两次,然后每次调用三次。当你添加其他产品时,数量会变得更加疯狂。 我无法弄明白错误的地方:(

希望你能帮助我;)

public static function addProduct($product_code) 

    {
        $db = JFactory::getDBO();
        //MySqli query - get details of item from db using product code
        $db->setQuery("SELECT product_name FROM #__osmaf_products WHERE product_code='$product_code' LIMIT 1");

        // Load the row.
        $result = $db->loadResult();

            //prepare array for the session variable
            $new_product = array(array('name'=>$result, 'code'=>$product_code, 'qty'=>1));

            if(isset($_SESSION["products"])) //if we have the session
            {
                $found = false; //set found item to false

                foreach ($_SESSION["products"] as $cart_itm) //loop through session array
                {
                    if($cart_itm["code"] == $product_code) //the item exist in array
                    {
                        $qty = $cart_itm["qty"]+1; //increase the quantit
                        $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$qty);
                        $found = true;
                    }
                    else
                    {
                        //item doesn't exist in the list, just retrive old info and prepare array for session var
                        $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"]);
                    }
                }

                if($found == false) //we didn't find item in array
                {
                    //add new user item in array
                    $_SESSION["products"] = array_merge($product, $new_product);
                }
                else
                {
                    //found user item in array list, and increased the quantity
                    $_SESSION["products"] = $product;
                }

            }
            else
            {
                //create a new session var if does not exist
                $_SESSION["products"] = $new_product;
            }
        return;

    }
}

1 个答案:

答案 0 :(得分:0)

尝试替换以下代码:

$db = JFactory::getDBO();
$db->setQuery("SELECT product_name FROM #__osmaf_products WHERE product_code='$product_code' LIMIT 1");

$result = $db->loadResult();

用这个:

$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select($db->quoteName('product_name'))
 ->from($db->quoteName('#__osmaf_products'))
 ->where($db->quoteName('product_code') . ' = '. $db->quote($product_code));

$db->setQuery($query, 0, 1);
$results = $db->loadObjectList();