[英]Product filter - count products
I've made a simple product filter in php, mysql and jquery. 我在php,mysql和jquery中做了一个简单的产品过滤器。 I have a database named "spec_laptop" and I select products after column named "brand".
我有一个名为“ spec_laptop”的数据库,我在名为“ 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:
<?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和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. 您的HTML代码似乎在php文件中,因为您也在其中使用php短代码。 So, I would recommend using php to display the options via a select query and loop.
因此,我建议使用php通过选择查询和循环显示选项。 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
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.