检查包含逗号分隔字符串的 sql 列

问题描述 投票:0回答:1

我尝试使用 FIND_IN_SET、LIKE %word% 和其他方式但没有成功..

好的,现在我有一个包含列 field_name 的表,并且有多个结果.. 插入的值如下:

Internet
Security
Furnished and so on...

我尝试检查我的字符串是否包含在上面此列中传递的单词.. 我的字符串是:

"Internet, Security"
,我必须检查这个字符串是否从上面的值传递了
field_name
列。

这是我的代码:

function check_osobenosti($value,$id_field) {
    global $dbh;
    //proceed
    $trim_v = trim($value);
    $query2 = $dbh->query("SELECT `field_name` FROM wpls_sw_field_lang  WHERE FIND_IN_SET('".$trim_v."',`field_name`) > 0  AND `field_id`='".(int)$id_field."'");
    if($query2->rowCount() > 0) {
        return 1;
    } else {
        return '';
    }
}

$value
我从上面传递字符串,它是:
"Internet, Security"

我想检查这个字符串是否包含在上述字段之一中.. 我不知道该怎么做,因为我是新手。

php mysql string concatenation
1个回答
0
投票

我会使用

IN()
并参数化查询:

function check_osobenosti(string $value, int $id_field) {
    global $dbh;
    
    // split $value into an array to pass when executing the prepared statement
    // splitting on ',' instead of ', ' so that it can handle either
    $toBind = explode(',', $value);
    $toBind = array_map('trim', $toBind);
    
    // build string of '?' placeholders for IN()
    $inPlaceholders = rtrim(str_repeat('?,', count($toBind)), ',');

    // add the $id_field to the array to be passed to execute
    $toBind[] = $id_field;

    // prepare the SQL statement    
    $query = $dbh->prepare("SELECT COUNT(*) FROM wpls_sw_field_lang WHERE `field_name` IN ($inPlaceholders) AND `field_id` = ?");
    
    // execute the prepared statement
    $query->execute($toBind);
    
    if($query->fetchColumn() > 0) {
        return 1;
    } else {
        return '';
    }
}

我已将查询更改为

COUNT(*)
,因为您没有使用返回的数据,而不是计算返回的记录。您不应该将 PDOStatement::rowCount() 与 SELECT 语句一起使用:

对于大多数数据库,PDOStatement::rowCount() 不返回受 SELECT 语句影响的行数。相反,使用 PDO::query() 发出一个 SELECT COUNT(*) 语句,其谓词与您预期的 SELECT 语句相同,然后使用 PDOStatement::fetchColumn() 检索匹配行数。

© www.soinside.com 2019 - 2024. All rights reserved.