0

我有一个带有多个复选框的 html 表单。我将这些传递给php ...

例如,值将像“G,BW”一样出现(“BW,G”也需要匹配)在 check.php 中,我需要从 $_GET 中获取值并修改它们以进行 sql 查询......

<?php
if(!empty($_GET['wireColor'])) {
    foreach($_GET['wireColor'] as $colors) {
    echo $colors; //make sure it's right, then comment out
    }
}

$colors = rtrim($colors, ','); //Get rid of trailing , - not working right

$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\''; //Trying to add the sql bits to pass to the query.

理想情况下要通过:

$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' and wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' );";

以下是查询在结尾的样子:

SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)G(,|$)' and wire_colors REGEXP '.*(^|,)BW(,|$)' );

我很难将正则表达式位放入查询中。

更新

这是我现在拥有的:

<?php
if(!empty($_GET['wireColor'])) {
    foreach($_GET['wireColor'] as $colors) {
        $wireSearch = ' REGEXP \'.*(^|,)' .$colors.'(,|$)\' AND ';
    }
}

$Search = rtrim($wireSearch, 'AND'); //Trying to trim the last "AND"
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors $wireSearch% );";

这主要给了我我需要的东西,但是打印/回显结果,我得到:

$wireSearch 最终结果是:REGEXP '.*(^|,)G(,|$)' AND REGEXP '.*(^|,)BW(,|$)' AND这很棒——我只需要核对最后一个“AND”。不过,上面的修剪将其替换为第二个值。诡异的。

和 $colors_lookup_sql 最终为:SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)BW(,|$)' AND % );

但是由于某种原因,数组中的第一个值消失了,我不明白,因为它出现在 sql 语句之前。

4

3 回答 3

1

I'm not sure about the REGEX inside the query since I haven't used it but:

$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\'';

Here you have a problem, the variable $wireColor is inside a string, and you are using ' so anything inside is not read as a variable, it should be something like:

$wireSearch = '\'REGEXP \'.*(^|,)'.$wireColor.'(,|$)\'';
于 2013-07-03T06:16:46.193 回答
0

我猜mysql正则表达式支持单词边界,怎么样:

wire_colors REGEX '\bBW\b' and wire_colors regex '\bW\b'
于 2013-07-03T09:40:10.603 回答
0

我不能说我完全了解您的数据是如何存储的,而且我自己也没有经常使用 REGEX,但也许这样的事情会更容易使用:

$wireSearch = explode(",", $_GET['wireColor']);
$query = "SELECT * FROM parts WHERE wire_colors LIKE '%$wireSearch[0]%' 
         AND wire_colors LIKE '%$wireSearch[1]%'";

不确定这是否有帮助,但我认为我会提出这个想法。

于 2013-07-03T07:16:24.953 回答