0

我正在尝试在类别页面上进行电子商务过滤。到目前为止,我可以让它为一种颜色工作,但如果用户检查不止一种颜色,我希望它也搜索另一种颜色。

网址

//current
category.php?colourChoice=White
//more than one
category.php?colourChoice=White&colourChoice=Ruby+Red

我意识到我需要某种形式的数组或爆炸?

MYSQL

products
---
id      sku     price
1       p22     45.00
2       p33     65.00   
3       p44     70.00

colours
---
id      sku     name
1       p22     White
2       p33     Ruby Red    
3       p44     Black

HTML

<form action="form.php" method="get">
    <input type="checkbox" name="colourChoice" value="White"/>
    <input type="checkbox" name="colourChoice" value="Black"/>
    <input type="checkbox" name="colourChoice" value="Ruby Red"/>
    <input type="checkbox" name="colourChoice" value="Orange"/>
    <input type="submit" value="go">
</form>

PHP

// VARS
$colourName=mysql_real_escape_string($_GET["colourChoice"]);

// MYSQL
$checkSQL=mysql_query("
    SELECT * FROM `products`
    INNER JOIN `colours`
    ON `products`.`sku` = `colours`.`sku`
    WHERE (
    name = '".$colourName."'
        OR name LIKE '".$colourName.";%'
        OR name LIKE '%;".$colourName.";%'
        OR name LIKE '%;".$colourName."'
    )
");

// SHOW RESULTS
while($r = mysql_fetch_array($checkSQL)) {
    echo '
        <div class="product">
            Cost £'.$r['price'].'<br />
        </div>
    ';
}
4

2 回答 2

1

你必须使复选框数组如下

<form action="form.php" method="get">
    <input type="checkbox" name="colourChoice[]" value="White"/>
    <input type="checkbox" name="colourChoice[]" value="Black"/>
    <input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
    <input type="checkbox" name="colourChoice[]" value="Orange"/>
    <input type="submit" value="go">
</form>

然后,您将在 php.ini 中将多个值签入数组。

foreach($_GET["colourChoice"] as $value){
  /// here you can make concat for where clause.
}
于 2012-10-04T08:43:01.503 回答
0

您可以在 PHP 中将 HTML 输入值作为数组获取:

HTML

<form action="form.php" method="get">
    <input type="checkbox" name="colourChoice[]" value="White"/>
    <input type="checkbox" name="colourChoice[]" value="Black"/>
    <input type="checkbox" name="colourChoice[]" value="Ruby Red"/>
    <input type="checkbox" name="colourChoice[]" value="Orange"/>
    <input type="submit" value="go">
</form>

然后使用准备/执行语句查询数据库以防止 SQL 注入。

PHP

$placeholders = substr(str_repeat('?, ', count($_GET['colourChoice']), 0, -1);
$query = "
    SELECT * FROM `products`
    INNER JOIN `colours`
    ON `products`.`sku` = `colours`.`sku`
    WHERE name in ($placeholders);
");
$db = new PDO(...);
$stmt = $db->prepare($query);
$stmt->execute($_GET['colourChoice']);
print_r($stmt->fetchAll());
于 2012-10-04T08:45:41.953 回答