【发布时间】:2022-01-22 12:23:54
【问题描述】:
MySQL 版本是10.1.19-MariaDB。
PHP版本为7.0.13。
我有一张桌子叫words2:
CREATE TABLE words2 (word varchar(64));
INSERT INTO words2 VALUES ('ABSCESS'), ('ABSCISE'),('ABSCOND'),('ABSENCE');
INSERT INTO words2 VALUES ('ABSINTH'), ('ABSOLVE'), ('ABSTAIN');
INSERT INTO words2 VALUES ('ACCORDS'), ('ACCRUES'), ('ASCENDS');
SELECT * FROM words2 ORDER BY 1;
+---------+
| word |
+---------+
| ABSCESS |
| ABSCISE |
| ABSCOND |
| ABSENCE |
| ABSINTH |
| ABSOLVE |
| ABSTAIN |
| ACCORDS |
| ACCRUES |
| ASCENDS |
+---------+
现在,我想运行一个查询,列出以'ABS' 开头但不包含'O' 或'D' 的单词。
在 MySQL 客户端中,我运行:
select upper(word) word
from words2
where lower(word) like lower('abs%')
and regexp_instr(lower(word), '[od]' ) = 0
order by 1;
正确给出:
+---------+
| word |
+---------+
| ABSCESS |
| ABSCISE |
| ABSENCE |
| ABSINTH |
| ABSTAIN |
+---------+
在 PHP 中,我有以下内容:
$matchchars = 'abs%';
$ignore = '[od]';
$sql = 'select upper(word) word from words w where lower(word) like ? ';
$sql .= ' and regexp_instr(lower(word), ?) = 0 ';
$sql .= ' order by upper(word)';
$stmt = $dbh->prepare($sql);
$stmt->bind_param('ss', $matchchars, $ignore);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
$num_rows = $result -> num_rows;
echo 'Num rows: '. $num_rows;
但这会返回 0 行。 如果我删除第二个 WHERE 条件,以便我拥有:
$matchchars = 'abs%';
$sql = 'select upper(word) word from words w where lower(word) like ? ';
$sql .= ' order by upper(word)';
$stmt = $dbh->prepare($sql);
$stmt->bind_param('s', $matchchars);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
$num_rows = $result -> num_rows;
echo 'Num rows: '. $num_rows;
我得到了预期的结果。
使用包含 REGEXP_INSTR 正则表达式的绑定变量是否有问题?
【问题讨论】:
-
顺便说一下,请升级到更现代的 PHP 版本。 PHP 7.0 已经很老了,根本不再支持 PHP 7。这是为了您自己的安全和利益
-
呃,MariaDB 不是 MySQL - 这就是它的全部意义所在。
-
使用不区分大小写 (..._ci) 的排序规则,然后去掉所有的
UPPER()s和LOWER()s。
标签: php mysql regex bind-variables