1

My PHP statement looks like this

 $select_product= "SELECT * FROM `products` WHERE pro_name = '$page_name' and status = 'Active'";
 $sql101=$dbconn->prepare($select_product);
 $sql101->execute();
 $wlvd101=$sql101->fetchAll(PDO::FETCH_OBJ);
 foreach($wlvd101 as $rows101);
 
 $product_id = $rows101->id;
 // Gives me result of a sample id 101

Again I am another statement where I have fetched the ids of products from my cart. The statement looks like this:

$pidArr = array();
if(!empty($_SESSION['cart'])){
    
    foreach($_SESSION['cart'] as $id=>$val)
    {
        $rate=$val['product_mrp'] * $val['qty'];
        $total=$total+$rate;
        $pidArr[] = $val['uid'];
        $qtyArr[] = $val['qty'];
        $webArr[] = $val['ppid'];
    }
    $all_cart_products = "'" . implode("','", $pidArr) . "'";  
    //echo $all_cart_products;

    //It gives me a list of ids like this '100', '101', '102' etc
}

Now while using in_array, my statement is not working. The code looks like this:

$my_ids = $all_cart_products;

if (in_array("$product_id", $my_ids))
{
  echo "Match Found";
}
else
{
  echo "Match not found";
}

How to solve this problem?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • What error do you get? Did you call `session_start()` before calling the `$_SESSION` superglobal? – Pieterjan Sep 23 '20 at 09:36
  • 2
    it's normal $all_cart_products are not an array, made a var_dump of $all_cart_products; before your if (in_array("$product_id", $my_ids)) – Inazo Sep 23 '20 at 09:39
  • What do you mean by "not working"? What have you tried to debug the problem? – Nico Haase Sep 23 '20 at 09:40
  • Please read up on: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – floGalen Sep 23 '20 at 09:41

1 Answers1

4

This line $all_cart_products = "'" . implode("','", $pidArr) . "'" creates a string.

Which you then assign $my_ids = $all_cart_products; so $my_ids is also now a string.

Pass it $pidArr instead.

AntG
  • 1,291
  • 2
  • 19
  • 29