0

I have this problem that if the item exist in the cart table, it will update quantity but if I add another item which doesn't exist, it doesn't work. If the cart table is empty it works, in short how could I insert another product which doesn't exist? Thanks in advance.

if(!empty($_POST["quantity"])) {
    $productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
    $cart_item = $db_handle->runQuery("SELECT * FROM `cart`");

    if(!empty($cart_item)){
        $code = $_GET["code"];
        $query = "SELECT code FROM `cart` WHERE code='" . $_GET["code"] . "'";
        $quantityByCode = $db_handle->runQuery("SELECT * FROM cart WHERE code='" . $_GET["code"] . "'");
        $nQuan = $quantityByCode[0]["quantity"] + $_POST["quantity"];
        if($query = $code){
            $db_handle->runQ("UPDATE cart SET quantity = ".$nQuan." WHERE code='" . $_GET["code"] . "'");
        }else{
            $db_handle->runQ("INSERT INTO cart (`name`, `code`, `size`, `quantity`, `price`, `cond`)VALUES ('". $productByCode[0]["name"] ."', '". $productByCode[0]["code"] ."' ,'". $productByCode[0]["size"] ."',". $_POST["quantity"] .",". $productByCode[0]["price"] .",1)");
        }

    }else{
        $query="INSERT INTO cart (`name`, `code`, `size`, `quantity`, `price`, `cond`) VALUES ('". $productByCode[0]["name"] ."', '". $productByCode[0]["code"] ."' ,'". $productByCode[0]["size"] ."',". $_POST["quantity"] .",". $productByCode[0]["price"] .",1)";
                $is_query_successful=mysql_query($query);
    }
}
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
Sibi
  • 61
  • 6
  • try `mysql_query($query)` which u have used when cart is empty – teju c Nov 28 '17 at 17:41
  • it works if empty, the only problem was when i add another product than the exist one, it wont add and the exist one will remain the same – Sibi Nov 28 '17 at 17:52
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 28 '17 at 18:14
  • 1
    Don't use the `mysql_*` functions. They have been deprecated since v5.5 (Jun 2013) and removed since v7.0 (Dec 2015). Instead use the [**mysqli_***](https://secure.php.net/manual/en/book.mysqli.php) or [**PDO**](https://secure.php.net/manual/en/book.pdo.php) functions with [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) and [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). – Alex Howansky Nov 28 '17 at 18:14

0 Answers0