Using REGEXP inside mysqli prepared statement in P

2019-07-04 02:46发布

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.

2条回答
成全新的幸福
2楼-- · 2019-07-04 03:09

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.

查看更多
Animai°情兽
3楼-- · 2019-07-04 03:22

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);
查看更多
登录 后发表回答