简体   繁体   English

MySQL REGEXP与?占位符如何与php变量绑定

[英]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 ). 想使用'111|114|115'作为php变量(例如$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 ) $data看起来像Array ( [0] => 111| [1] => 114| [2] => 115 )

After execution of statement get SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s) . 执行语句后获取SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)

Suppose something not correct with $data = array('111|', '114|', '115'); 假设$data = array('111|', '114|', '115');不正确$data = array('111|', '114|', '115');

What is correct code? 什么是正确的代码?

This means that REGEXP expects only one placeholder, but you are giving it three. 这意味着REGEXP只需要一个占位符,但是你给它三个。

Change this: 改变这个:

$sql->execute($data);

to: 至:

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

You give 3 params to regexp while it should be only one: 你给3个参数regexp而它应该只有一个:

... 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: char对一些数组元素,你可以做这样的事情:

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

And then just use one param binding in your SQL query.: 然后在SQL查询中使用一个param绑定:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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