Using REGEXP inside mysqli prepared statement in PHP

最后都变了- 提交于 2019-12-23 18:50:59

问题


I am trying to make a simple search process with (noob) codes like this:

$prep->prepare("SELECT * FROM details WHERE id REGEXP '?'");
$prep->bind_param("s", $search_query);

It gives me this warning:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

I am guessing it could be because the question mark is also used for RegExp (optional previous character).

Any idea about how to use REGEXP inside prepared statements (without conflicting question marks)?

Thanks.


回答1:


Take out the single quotes around the ?. Your code should read:

$prep->prepare("SELECT * FROM details WHERE id REGEXP ?");
$prep->bind_param("s", $search_query);

As it stands now, you are passing in one param, but the ? in single quotes is treated as a string, not a parameter marker.




回答2:


What Ed responded is correct.

However, if you happen to need more complex regular expressions, you can use CONCAT to create the expression.

// Target SQL
//    SELECT * FROM `table` WHERE `field` REGEXP "value1|value2|value3";
// Target Prepared Statement SQL
//    SELECT * FROM `table` WHERE `field` REGEXP ?|?|?;
$sql = 'SELECT * FROM `table` '
     . 'WHERE `field` REGEXP CONCAT(?, "|", ?, "|", ?)';
$bindings = [$value1, $value2, $value3];

$prepStmt = $db->prepare($sql);
$prepStmt->execute($bindings);


来源:https://stackoverflow.com/questions/21890498/using-regexp-inside-mysqli-prepared-statement-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!