What wrong about this code

   $total = 0;
   if(isset($_SESSION['cart']))
   {
		$count = count($_SESSION['cart']);	
		
		$product_id = array_column($_SESSION['cart'], 'product_id');
		
		//Array ( [0] => Array ( [product_id] => 5 ) [1] => Array ( [product_id] => 4 ) [2] => Array ( [product_id] => 3 ) ) 
		print_r($_SESSION['cart']);	
		echo "<br>" ;

		$query = "SELECT * FROM product";
		$data = $dbh -> query($query);
        $data->execute();
		
		while($row = mysql_fetch_array($data));	{		
			foreach ($product_id as $id) {
				if($row['id'] == $id){
					print $row["ProductName"] . "-" . $row["Discription"] . "-" . $row["Price"] ."<br/>";
					
					$total = $total + (int)$row['Price'];
				} 				
			}
		}
		
	   echo $total;

		
					
   }

To put it simply it’s using obsolete code as it should be using mysqli or PDO. There are plenty of good tutorials out there that show how to write mysqli or PDO (my recommendation).

1 Like

What wrong about this code?

Technically, it is mixing up database statement calls, which won’t work. All the database statements must be from the same extension. As @Strider64 stated, the PDO extension is the best, and simplest choice, for either updating old code or writing new code.

Functionally, just about everything else in the code has an issue. Some of them -

  1. If the session cart isn’t set or it is empty, you should display a message stating so. The current code does nothing, leaving the visitor wondering what did/should occur on a page.
  2. You are getting a count() of the elements in the cart, but not using that value. Don’t write code for nothing.
  3. The cart’s array index should be the product id. This will let you directly test/access the products in the cart by their id. The value you store in the elements in the cart should be the quantity, even if the quantity will always be an implied 1.
  4. To query to get the data matching the products in the cart, use a WHERE clause in the query, rather than to query for all products.
  5. Use a prepared query when supplying external, unknown, dynamic data values to a query when it gets executed. You can use a FIND_IN_SET() comparison in the WHERE clause so that you only need a single prepared query place-holder.
  6. When you loop over the result from the query, which will now only contain data for the products in the cart, to display the contents of the cart, access the quantity of each product in the cart (this is one place where using the product id as the cart’s index comes in handy) to calculate a sub-total for each product, that you display for each product, and add to the total. Note: prices are typically decimal values, not integers. There’s no good reason to cast the data type of the price at all.
Sponsor our Newsletter | Privacy Policy | Terms of Service