Skip to content
Advertisement

search products by checkbox in ecommerce shoping cart system in codeigniter php

I am using CodeIgniter to build ecommerce project in which i am working on search products from database by multiple filter parameters with checkboxes.

But i am not getting correct results. First i have check Brand->Dell it gets two products , after that i checked Ram-> 5 GB so it does not changes but i want it shows only 1 product of 5 GB Ram with DELL Brand.

enter image description here

Model

    <?php
    class ProductsM extends CI_Model {
    
    public function getRowsByCheck($keyword){
    if($keyword=="")
    {
      $search_keuword = '';
    }
    else
    {
     $search_keuword = "and brand IN ('".$keyword."') OR ram IN ('".$keyword."') OR price IN ('".$keyword."')"; 
    }

$query = $this->db->query("SELECT * FROM products WHERE products_id!='' " . $search_keyword . "");
    
          if($query->num_rows() > 0){                       
        $product   = $query->result_array(); 
        return $product;               
        }       
        else{
            
            echo "<div class='btn-success btn-block' align='center'><strong>NO Related Product Found!!!</strong></div>";
        }
     }
    }?>

Controller

class ProductsC extends CI_Controller {
public function fetchByCheck(){
   $output='';
    $keyword='';
    if($this->input->post('tmp')){
      $array = $this->input->post('tmp');
      $keyword = implode("','",$array);
    }
    $data = $this->productsM->getRowsByCheck($keyword);
       foreach ($data as $p) {
  $output.='<div class="col-md-4">
      <div class="panel panel-info">
          <div class="panel-heading">'.$p["name"].'</div>
          <div class="panel-body" align=center>
          <img src="'.base_url("assets/images/".$p['image']).'" style="height:100px;">
          </div>
          <div class="panel-heading">Rs.'.$p["price"].'
      <a href="'.base_url()."ProductsC/addToCart/".$p['id'].'" class="btn btn-success">Add To Cart</a>
          Ram '.$p["ram"].'GB</div>
        </div>
        </div>';
       }
    echo   $output;
  }
}?>

View

div class="list-group">
                <h3>BRAND</h3>
                <?php
                foreach($brand_data as $row){?> 
                  <div class="list-group-item checkbox">
                    <label><input type="checkbox" class="common-selector brand searchType"
                      value="<?php echo $row['brand'];?>"><?php echo $row['brand'];?></label>  
                  </div>
              <?php } ?>
            </div>    

            <div class="list-group">
                <h3>RAM</h3>
                  <?php
                foreach($ram_data as $row){?> 
                  <div class="list-group-item checkbox">
                    <label><input type="checkbox" class="common-selector ram searchType" 
                      value="<?php echo $row['ram'];?>"><?php echo $row['ram'];?></label>  
                     </div>
               <?php } ?>
            </div>  

Script.js

<script type="text/javascript">
  $(document).ready(function(){
$('.searchType').on('click', function () {
  var tmp = [];
      $("input").each(function() {
          if ($(this).is(':checked')) {
          var checked = ($(this).val());
          tmp.push(checked);
        }
      });
  //alert(tmp);

$.ajax({
              url:"<?php echo base_url();?>ProductsC/fetchByCheck",
              method:"POST",
              data:{tmp:tmp},
              success:function(data){
                //alert(data);
                $('#result').html(data);
              }
        });
});
});
</script>

Advertisement

Answer

You use an OR condition on your query, this will always result true if one of the optional keyword is supplied. In order to set to all condition, you could split each of the keywords and use AND condition :

HTML

<div class="list-group">
    <h3>BRAND</h3>
    <?php
    foreach ($brand_data as $row) { ?>
        <div class="list-group-item checkbox">
            <label><input type="checkbox" name="brand" class="common-selector brand searchType" value="<?php echo $row['brand']; ?>"><?php echo $row['brand']; ?></label>
        </div>
    <?php } ?>
</div>

<div class="list-group">
    <h3>RAM</h3>
    <?php
    foreach ($ram_data as $row) { ?>
        <div class="list-group-item checkbox">
            <label><input type="checkbox" name="ram" class="common-selector ram searchType" value="<?php echo $row['ram']; ?>"><?php echo $row['ram']; ?></label>
        </div>
    <?php } ?>
</div>

Javascript

<script type="text/javascript">
    $(document).ready(function() {
        $('.searchType').on('click', function() {
            var tmp_brand = [];
            $("input[name='brand']").each(function() {
                if ($(this).is(':checked')) {
                    var checked = ($(this).val());
                    tmp_brand.push(checked);
                }
            });
            var tmp_ram = [];
            $("input[name='ram']").each(function() {
                if ($(this).is(':checked')) {
                    var checked = ($(this).val());
                    tmp_ram.push(checked);
                }
            });
            //alert(tmp);

            $.ajax({
                url: "<?php echo base_url(); ?>ProductsC/fetchByCheck",
                method: "POST",
                data: {
                    tmp_brand: tmp_brand,
                    tmp_ram: tmp_ram,
                    tmp_price: tmp_price
                },
                success: function(data) {
                    //alert(data);
                    $('#result').html(data);
                }
            });
        });
    });
</script>

Controller

<?php

class ProductsC extends CI_Controller
{
    public function fetchByCheck()
    {
        $output = '';
        $keyword = [];
        if ($this->input->post('tmp_ram')) {
            $array = $this->input->post('tmp_ram');
            $keyword['ram'] = implode("','", $array);
        }
        if ($this->input->post('tmp_brand')) {
            $array = $this->input->post('tmp_brand');
            $keyword['brand'] = implode("','", $array);
        }
        if ($this->input->post('tmp_price')) {
            $array = $this->input->post('tmp_price');
            $keyword['price'] = implode("','", $array);
        }
        $data = $this->productsM->getRowsByCheck($keyword);
        foreach ($data as $p) {
            $output .= '<div class="col-md-4">
      <div class="panel panel-info">
          <div class="panel-heading">' . $p["name"] . '</div>
          <div class="panel-body" align=center>
          <img src="' . base_url("assets/images/" . $p['image']) . '" style="height:100px;">
          </div>
          <div class="panel-heading">Rs.' . $p["price"] . '
      <a href="' . base_url() . "ProductsC/addToCart/" . $p['id'] . '" class="btn btn-success">Add To Cart</a>
          Ram ' . $p["ram"] . 'GB</div>
        </div>
        </div>';
        }
        echo   $output;
    }
} ?>

Model

<?php
class ProductsM extends CI_Model
{

    public function getRowsByCheck($keyword)
    {
        $search_keuword = '';
        if (count($keyword) > 0) {
            foreach ($keyword as $key => $value) {
                if ($key == 'ram') {
                    $search_keuword .= "and ram IN ('" . $value . "')";
                }
                if ($key == 'brand') {
                    $search_keuword .= "and brand IN ('" . $value . "')";
                }
                if ($key == 'price') {
                    $search_keuword .= "and price IN ('" . $value . "')";
                }
        }
        $res = $this->db->query("SELECT * FROM products WHERE id!='' " . $search_keuword . "")->result_array();
        return $res;
    }
} ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement