带AND运算符的正则表达式mysql

时间:2019-02-19 09:19:18

标签: php html mysql regex

我已经创建了一个搜索字段,如果我搜索“菠菜,西瓜”,它将以“,”爆炸输入,并运行MySQL搜索数据库。这意味着SQL将以

运行
SELECT * FROM table WHERE 
(vegetable LIKE '%Spinach%' OR fruits LIKE '%Spinach%') AND (vegetable LIKE '%Watermelon%' OR fruits LIKE '%Watermelon%')

我的数据库表数据看起来像这样:

id  Vegetable  fruits
----------------------
1   Spinach    Apple
2   Cucumber   Orange
3   Spinach    Watermelon

每个id的结果只能显示一次。

<php>
$keywords = trim($_REQUEST['keyword']);
$keywords = preg_replace("/,\s*/", "|", $keyword);
$where = "[[:<:]](" . $keywords . ")[[:>:]]";

$sql = "SELECT * FROM table ";
$sql .= "WHERE vegetable REGEXP '" . $where . "' OR fruits REGEXP '" . $where . "'";
$result = mysqli_query($conn, $sql);
while ($rs = mysqli_fetch_array($result)) 
{
    $vege = $rs["vegetable"];
    $fruits = $rs["fruits"];
}

</php>


<html>
<form method=post>
    <input type="text" class="form-control" placeholder="SEARCH..." value="<?=$keywords?>">
</form>
</html>

1 个答案:

答案 0 :(得分:1)

以下是使用REGEXP的文字MySQL查询:

SELECT *
FROM table
WHERE
    (vegetable REGEXP '[[:<:]]Spinach[[:>:]]' OR fruits REGEXP '[[:<:]]Spinach[[:>:]]') AND
    (vegetable REGEXP '[[:<:]]Watermelon[[:>:]]' OR fruits REGEXP '[[:<:]]Watermelon[[:>:]]');