如何在foreach循环中运行查询?

时间:2018-12-28 11:39:59

标签: php codeigniter mysqli

我有一个查询,该查询在foreach循环内运行,但仅在以下代码中立即运行,如下所述:

public function functional_job($functional)
    {
        $functions = explode(",",$functional);
        foreach($functions as $row)
        {
            $this->db->select('*');
            $this->db->from('job');
            $this->db->where('functional',$row);
            $query = $this->db->get();if($query->num_rows()>0)
            {
                $result = $query->result_array();
                return $result;
            }
            else
            {
                $this->session->set_flashdata('msg','<p style="color:red;font-weight: 600;">No Job Found.</p>');
            }
        }
    }

其中$functional = IT,marketing,ecommerce。当我点击查询时,它仅运行SELECT * FROM job WHERE functional = 'IT'之类的查询。但我希望它运行3次,即SELECT * FROM job WHERE functional = 'IT' SELECT * FROM job WHERE functional = 'marketing' SELECT * FROM job WHERE functional = 'ecommerce'

1 个答案:

答案 0 :(得分:0)

您的代码将返回一个结果的值并停止处理。

您可以更改代码以将结果存储在数组中,然后将其返回?

public function functional_job($functional){

    $functions = explode(",",$functional);

    $results = array();

    foreach($functions as $row)
    {
        $this->db->select('*');
        $this->db->from('job');
        $this->db->where('functional',$row);
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
            $results[] = $query->result_array();
        }
        else
        {
            $this->session->set_flashdata('msg','<p style="color:red;font-weight: 600;">No Job Found.</p>');
        }
    }

    return $results;
}

如上所述,您还可以更改查询以使用MySql的IN功能。

SELECT * FROM job WHERE functional IN ('IT', 'marketing', 'ecommerce')

如果不知道codeigniter,它可能看起来像这样:

$this->db->select('*');
$this->db->from('job');
$this->db->where_in('id', $functional);
$query = $this->db->get();