I have a query which is not constant all the time ..., In fact it will be generate according to some factor. And it is sometimes like this:
我有一个查询,它一直不是常数...,实际上它将根据某些因素生成。它有时像这样:
select * from table1 where id = :id
And sometimes else it could be like this:
有时它可能是这样的:
select * from table1 where id = :id
union all
select * from table2 where id = :id
And sometimes else it maybe be like this:
有时候它可能是这样的:
select * from table1 where id = :id
union all
select * from table2 where id = :id
union all
select * from table3 where id = :id
Already: I used PHP version 5.2.6 so far and it was completely fine. I mean is, I just passed one time :id
parameter and I could use it for multiple times in the query. Just this:
已经:到目前为止我使用的是PHP版本5.2.6,它完全没问题。我的意思是,我刚刚传递了一次:id参数,我可以在查询中多次使用它。只是这个:
$stm->bindValue(':id', $id, PDO::PARAM_INT);
This ^ was good for all those above queries.
这对所有上述查询都很好。
Now: I have updated my PHP version (my current PHP version is 5.6.8). Well, As you know, in the new version, I cannot do that like former. I need to pass a separated parameter for every time that I want to use it in the query. like this:
现在:我已经更新了我的PHP版本(我当前的PHP版本是5.6.8)。嗯,如你所知,在新版本中,我不能像以前那样做。每次我想在查询中使用它时,我都需要传递一个单独的参数。喜欢这个:
For query1:
对于query1:
$stm->bindValue(':id', $id, PDO::PARAM_INT);
For query2:
对于query2:
$stm->bindValue(':id1', $id, PDO::PARAM_INT);
$stm->bindValue(':id2', $id, PDO::PARAM_INT);
For query3:
对于query3:
$stm->bindValue(':id1', $id, PDO::PARAM_INT);
$stm->bindValue(':id2', $id, PDO::PARAM_INT);
$stm->bindValue(':id3', $id, PDO::PARAM_INT);
So given that I don't know how many times I need to pass :id
parameter to the query (because my query is dynamic), How can I solve this problem?
所以鉴于我不知道我需要传递多少次:id参数到查询(因为我的查询是动态的),我该如何解决这个问题?
1 个解决方案
#1
1
You could store all id values in an array and iterate over it.
您可以将所有id值存储在一个数组中并迭代它。
This will work as long as all values are of same type (int) and your place holders are of the form :idNUMBER:
只要所有值的类型相同(int)并且占位符的格式为:idNUMBER:
$ids = array('what','ever');
for($c=0;$c<count($ids);$c++) {
$stm->bindValue(':id' . ($c+1), $ids[$c], PDO::PARAM_INT);
}
Not very elegant but will do the job.
不是很优雅但会完成这项工作。
A solution to even handle different types is described at http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli
http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli描述了处理不同类型的解决方案。
#1
1
You could store all id values in an array and iterate over it.
您可以将所有id值存储在一个数组中并迭代它。
This will work as long as all values are of same type (int) and your place holders are of the form :idNUMBER:
只要所有值的类型相同(int)并且占位符的格式为:idNUMBER:
$ids = array('what','ever');
for($c=0;$c<count($ids);$c++) {
$stm->bindValue(':id' . ($c+1), $ids[$c], PDO::PARAM_INT);
}
Not very elegant but will do the job.
不是很优雅但会完成这项工作。
A solution to even handle different types is described at http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli
http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli描述了处理不同类型的解决方案。