PHP implode 数组生成 mysql IN 标准
我有一个如下所示的函数:
public function foo ($cities = array('anaheim', 'baker', 'colfax') )
{
$db = global instance of Zend_Db_Adapter_Pdo_Mysql...
$query = 'SELECT name FROM user WHERE city IN ('.implode(',',$cities).')';
$result = $db->fetchAll( $query );
}
直到有人将 $cities 作为空数组传递为止,效果都很好。
为了防止这个错误,我一直在逻辑上破坏查询,如下所示:
$query = 'SELECT name FROM user';
if (!empty($cities))
{
$query .= ' WHERE city IN ('.implode(',',$cities).')';
}
但这不是很优雅。我觉得应该有一种更好的方法来按列表进行过滤,但我不确定如何做。有什么建议吗?
I have a function like the following:
public function foo ($cities = array('anaheim', 'baker', 'colfax') )
{
$db = global instance of Zend_Db_Adapter_Pdo_Mysql...
$query = 'SELECT name FROM user WHERE city IN ('.implode(',',$cities).')';
$result = $db->fetchAll( $query );
}
This works out fine until someone passes $cities as an empty array.
To prevent this error I have been logic-breaking the query like so:
$query = 'SELECT name FROM user';
if (!empty($cities))
{
$query .= ' WHERE city IN ('.implode(',',$cities).')';
}
but this isn't very elegant. I feel like there should be a better way to filter by a list, but I am not sure how. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您最终使用了 select 对象,
->where()
方法实际上会为您处理数组。仍然需要检查数组中是否有项目,但这使它成为一种更干净的方法......If you do end up using the select object the
->where()
method will actually handle arrays for you. Still need to check to see if there are items in the array, but this makes it a cleaner approach...至少使用
quote
方法...或者理想情况下,使用 Zend_Db_Select 构建查询...
At least use the
quote
method...or, ideally, construct the query with Zend_Db_Select...
所以你知道,来自 Zend_Db_Adapter::quote 的 Zend 文档
“如果将数组作为值传递,则数组值会被引用
* 然后以逗号分隔的字符串形式返回。”
所以你可以这样做,这也被正确引用:
我喜欢 1-liners :)
So you know, from Zend Docs of Zend_Db_Adapter::quote
"If an array is passed as the value, the array values are quoted
* and then returned as a comma-separated string."
So you could do this which is also quoted properly:
I love 1-liners :)