Jithin Varghese Jithin Varghese - 2 months ago 33
PHP Question

explode using foreach inside codeigniter model not working

I have a code which separate

,
from the string using explode.

Now the problem is the
foreach
loop only iterating once. Am using this code in
codeigniter model
.

My code is,

//Model

$product_id = '1,2,3';
$products = explode(',', $product_id);

foreach($products as $products_id) {
echo $products_id.'<br><br>'; //output: 1
$query = $this->db->query('SELECT * FROM tbl_products WHERE products_id = "'.$products_id.'" AND products_status = "1"');
$count = $query->num_rows();

if($count > 0) {
return $result = $query->result_array();
}
else {
return 0;
}
}


The output for the above code is
1
.

The other digit
2
and
3
is missing. Am I doing anything wrong. Please help me out. I can't figure it out.

Answer

To correct it, you could do this

    $product_id = '1,2,3';
    $products = explode(',', $product_id);
    $data = [];

    foreach($products as $products_id) {
        echo $products_id.'<br><br>'; //output: 1
        $query = $this->db->query('SELECT * FROM tbl_products WHERE products_id = "'.$products_id.'" AND products_status = "1"');
        $count = $query->num_rows();

        if($count > 0) {
            $data = array_merge($data, $query->result_array());
        }
    }

    if(empty($data)){
        return 0;
    } 
    return $data;

Which avoids exiting in the original if statement you return on more then 0 results or 0 results, so basically on the first iteration of the loop.

But, that said, possibly a better way to fix it is this

  $product_id = '1,2,3';

  $query = $this->db->query('SELECT * FROM tbl_products WHERE products_id IN( ? ) AND products_status = "1"',$product_id);
  $count = $query->num_rows();

  if($count > 0) {
        return $query->result_array();
  }else{
        return 0;
  } 

Using IN you can avoid the foreach,explode and additional query calls, also you should use prepared queries. This should work with numbers, but strings still need to be wrapped in quotes, 'IN( "string","string", "string" )' or $string = '"string","string","string"'; as the input, which may complicate things for prepared queries.