简体   繁体   English

如何在MySQL查询中使用foreach循环

[英]How to use foreach loop in mysql query

I want to add some condition to my sql select by using foreach loop. 我想通过使用foreach循环向我的sql select添加一些条件。 For example: 例如:

select id, custom_id, name, customer from db_clients where id = 5

By using foreach I want to and more "where" condition. 通过使用foreach,我希望获得更多“ where”条件。

select id, custom_id, name, customer from db_clients where id = 5 and id = 19

My PHP code: 我的PHP代码:

$this ='select id, custom_id, name, customer from db_clients where id = 5' . foreach($ids AS $id){
'. and id = '.$id}';

Where is the problem ? 问题出在哪儿 ?

$this ='select id, custom_id, name, customer from db_clients where id in ('.implode(',',$ids).') ';

这确实假定$ ids始终至少具有一个数组值,它可以为空,您需要在执行此操作之前添加另一条检查,或者添加-1或某些在数组中将永远不存在的id才可以确保填充它永远不会空虚,有很多方法可以处理空虚情况。

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

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