如何在N1QL中以相​​同的方式搜索字符串和整数?

时间:2016-07-08 11:44:07

标签: php couchbase n1ql

所以我有这个PHP函数:

public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
    $query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND `'.$field.'` LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
    $query->options['$collection'] = static::COLLECTION_NAME;
    //$query->options['$field'] = $field;
    $query->options['$limit'] = $recordsPerPage;
    $query->options['$offset'] = $recordsPerPage*($page-1);
    //$query->options['$searchterm'] = $searchterm;

    $result = DB::getDB()->query($query);
    //var_dump($query);
    //var_dump($result);
    $objects = array();
    foreach($result as $row) {
        $object = new static($row->{"public_portal"});
        $object->setId($row->{"public_portal"}->{"_id"});
        $objects[] = $object;
    }
    //var_dump($objects);
    return $objects;
}

此查询易受n1ql注入攻击。我知道。为什么?当我使用占位符(现在已注释)时,它没有给我任何结果。如果我无法修复,我会发布第二个问题。

我想问的问题是: 当用户搜索文档时,此函数成功查找文档。但是当字段是整数时,不会给出结果。我试图用" ="替换LIKE。并删除了引号和%。然后,用户可以成功搜索整数字段中的数字。但是,用户无法再搜索字符串字段。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我明白了。 我刚刚在n1ql语句中添加了一个TOSTRING(),它现在适用于string和int。

public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
    $query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
    $query->options['$collection'] = static::COLLECTION_NAME;
    //$query->options['$field'] = $field;
    $query->options['$limit'] = $recordsPerPage;
    $query->options['$offset'] = $recordsPerPage*($page-1);
    //$query->options['$searchterm'] = $searchterm;

    $result = DB::getDB()->query($query);
    //var_dump($query);
    //var_dump($result);
    $objects = array();
    foreach($result as $row) {
        $object = new static($row->{"public_portal"});
        $object->setId($row->{"public_portal"}->{"_id"});
        $objects[] = $object;
    }
    //var_dump($objects);
    return $objects;
    return $result;
}