简体   繁体   中英

MySQL REGEXP with ?placeholders how to bind with php variable

Here is working statement without ?

$query_select_all = "SELECT * FROM TableName WHERE CAST(ColumnName AS UNSIGNED) REGEXP '111|114|115'";
$sql = $db->prepare($query_select_all);
$sql->execute();

Want to use '111|114|115' as php variable (for example $data ).

Change code to

$data = array('111|', '114|', '115');
$query_select_all = "SELECT * FROM TableName WHERE CAST(ColumnName AS UNSIGNED) REGEXP (?,?,?)";
$sql = $db->prepare($query_select_all);
$sql->execute($data);

$data looks like Array ( [0] => 111| [1] => 114| [2] => 115 )

After execution of statement get SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s) .

Suppose something not correct with $data = array('111|', '114|', '115');

What is correct code?

This means that REGEXP expects only one placeholder, but you are giving it three.

Change this:

$sql->execute($data);

to:

$sql->execute(array('111|114|115'));

You give 3 params to regexp while it should be only one:

... REGEXP (?,?,?)";

So you finally get something like:

... REGEXP ('111|','114|','115')";

Moreover instead of adding | char to some of array elements, you could do something like this:

$res = implode('|', $arr);

And then just use one param binding in your SQL query.:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM