如何从 table 中获取具有字段和许多要检查字段的输入值的行?

how to get rows from table that have field and many input values to check against field?

我有一个 table 名称 wp_postmeta,一些字段是 meta_value,其中之一。我想输入 3 个值并检查 meta_value 字段。

$price = $_POST['prices'];
$city = $_POST['city'];
$hotels= $_POST['hotels'];

我的查询就像

SELECT post_id,meta_key,meta_value
    FROM `wp_postmeta`
    WHERE (`meta_value` LIKE '%$price%'  
    OR `meta_value` LIKE '%$hotels%'
    OR `meta_value` LIKE '%$city%')
   AND (meta_value IS NOT NULL)

在这里,如果我提供 3 个输入,那么它就可以了,如果我将一个字段留空以将 2 个输入值与 meta_value 进行比较,那么它将列出所有行

任何的想法??请分享。

试试,

$query = "SELECT post_id,meta_key,meta_value
    FROM `wp_postmeta` ";

$where = '';

if(trim($price) != '') {
$where .= "`meta_value` LIKE '%$price%'  ";
}

if(trim($hotels) != '') {
if($where != '') $where .= " OR ";
$where .= " `meta_value` LIKE '%$hotels%' ";
}

if(trim($city) != '') {
if($where != '') $where .= " OR ";
$where .= "`meta_value` LIKE '%$city%'";
}

if(trim($where) != '') {
$where = " WHERE ($where) AND (meta_value IS NOT NULL)";
} else {
$where = " WHERE (meta_value IS NOT NULL)";
}

$query = $query.$where;

并且,尝试使用 $query 代替 php 中的实际查询。

要与少于所有三个的变量进行比较,请完全删除适用于您不比较的变量的 where 子句部分:

不比较 $city:

SELECT post_id,meta_key,meta_value
    FROM `wp_postmeta`
    WHERE (`meta_value` LIKE '%$price%'  
    OR `meta_value` LIKE '%$hotels%')
   AND (meta_value IS NOT NULL)

一种方法是使用变量赋值:

$price = $_POST['prices'];
$city = $_POST['city'];
$hotels= $_POST['hotels'];

更改为:

$price = (isset($_POST['prices']) && trim($_POST['prices']) != '' ? filter_var($_POST['prices'],FILTER_VALIDATE_STRING) : null);

我使用的是 null,但您可以使用另一个可以保证不匹配的值。

另外,正如其他评论中提到的,一定要使用准备好的语句。