简体   繁体   中英

Product filter - count products

I've made a simple product filter in php, mysql and jquery. I have a database named "spec_laptop" and I select products after column named "brand". It looks like here and when I check shows me products with that "brand". I want to add before every checkbox option, the number of the products that have this "brand" in the database like this .

The code: PHP:

<?php
include ('connect.php');
if (isset($_POST["toshiba"])) {
  $arguments[] = "brand LIKE '%Toshiba%'";  
}
if (isset($_POST["lenovo"])) {
  $arguments[] = "brand LIKE '%Lenovo%'"; 
}
if (isset($_POST["samsung"])) {
  $arguments[] = "brand LIKE '%Samsung%'";
}
if(!empty($arguments)) {
  $str = implode(' or ',$arguments);
  $qry = "SELECT * FROM spec_laptop where " . $str . " ORDER BY id desc"; 
  $row=mysql_query($qry)  or die("Unable to select");


   while($data = mysql_fetch_array($row))
                            {

                                echo  $data['procesor']." ";
                            }

} else {
  echo "nothing";
}
?>

HTML & JAVASCRIPT:

<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form id="form" method="post" action="">
<input type="checkbox" name="toshiba" class="checkbox" <?=(isset($_POST['toshiba'])?' checked':'')?>/>Toshiba<?php ?><br>
<input type="checkbox" name="lenovo" class="checkbox" <?=(isset($_POST['lenovo'])?' checked':'')?>/> Lenovo<br>
<input type="checkbox" name="samsung" class="checkbox" <?=(isset($_POST['samsung'])?' checked':'')?>/>Samsung<br>
 </form>

 <script type="text/javascript">  
    $(function(){
     $('.checkbox').on('change',function(){
        $('#form').submit();
        });
    });
</script>

</body>
</html>

To get count in your query, change it from:

$qry = "SELECT * FROM spec_laptop where " . $str . " ORDER BY id desc";

to:

$qry = "SELECT *, count(id) as 'count' FROM spec_laptop where " . $str . " GROUP BY brand ORDER BY id desc";

Your HTML code seems like it is in a php file, since you are using php short code in there too. So, I would recommend using php to display the options via a select query and loop. A similar query to the one above can be used:

<?php
$qry = "SELECT brand as 'brandname', count(id) as 'count' FROM spec_laptop where " . $str . " GROUP BY brand ORDER BY id desc";
$row=mysql_query($qry)  or die("Unable to select");
?>
<form id="form" method="post" action="">
<?php
while($data = mysql_fetch_array($row))
{
?>
    <input type="checkbox" name="<?php echo $data['brandname'];?>" class="checkbox" <?php (isset($_POST['toshiba'])?' checked':'') ?>/><?php echo $data['brandname'] . ' [' . $data['count'] . ']';?><br>
<?php
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM