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

时间:2018-05-18 22:41:08

标签: php foreach

我想通过使用foreach循环为我的sql select添加一些条件。例如:

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

通过使用foreach我想和更多"其中"条件。

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

我的PHP代码:

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

问题出在哪里?

1 个答案:

答案 0 :(得分:1)

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

这确实假设$ ids总是至少有一个数组值,它可以是空的,你需要在这之前添加另一个检查,或者在填充之前添加​​一个-1或者一些永远不存在的id到数组中确保它永远不会是空的,有许多方法可以处理空洞的情况。