为了账号安全,请及时绑定邮箱和手机立即绑定

使用 foreach 循环时限制查询在 codeigniter 中不起作用

使用 foreach 循环时限制查询在 codeigniter 中不起作用

PHP
肥皂起泡泡 2022-01-24 09:12:46
我正在尝试使用以下查询限制 foreach 循环中的分页结果,但我没有限制我使用以下查询获得所有结果。public function get_tags($limit, $start, $tag_id){        $snippetstagdata = $this->getDataOneColumn("snippets_tags","tag_id",$tag_id);    foreach ($snippetstagdata as $getSnippet) {        $snippet_id = $getSnippet->snippet_id;        $this->db->where("id", $snippet_id);        $this->db->select('*');        $this->db->from('snippets');        $this->db->limit($limit, $start);        $query = $this->db->get();        $result[] = $query->result();    }    $this->db->save_queries = false;    return $result;}然而 getDataOneColumnpublic function getDataOneColumn($table, $col1_name, $col1_value){    $this->db->where("$col1_name", $col1_value);    $query = $this->db->get("$table");    $result = $query->result();    $this->db->save_queries = false;    return $result;}更新
查看完整描述

2 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您在 foreach 循环的帮助下查询数据库的方法是错误的。正确的方法是在查询中使用连接:


从您的函数getDataOneColumn()中,您仅使用snippet_id 值,您可以使用它来创建连接:


public function getDataOneColumn($table, $col1_name, $col1_value, $limit, $start)

{

    $this->db->select("t1.*,t2.*")

             ->where("t1.$col1_name", $col1_value)

             ->join("snippets t2","t1.snippet_id=t2.id")

             ->limit($limit, $start);


    $query = $this->db->get("$table t1");

    $result = $query->result();


    return $result;

}

注意:在您的示例$tag_id=$col1_value中,请使用更适合的任何变量名称。


那么你的第二个功能get_tags()就完全没有必要了。


查看完整回答
反对 回复 2022-01-24
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

我希望这能帮到您


public function get_tags($params = array(), $tag_id)

{   $result = array();

    $snippetstagdata = $this->getDataOneColumn("snippets_tags","tag_id",$tag_id);

    foreach ($snippetstagdata as $data) {

                $this->db->where('id',$data['snippet_id']);

        if(isset($params) && !empty($params))

        {

            $this->db->limit($params['limit'], $params['offset']);

        }

        $result[$data['snippet_id']] = $this->db->get('snippets')->result_array();

    }

    return $result;

}


public function getDataOneColumn($table, $col1_name, $col1_value)

{

    return $this->db->get_where($table,array($col1_name=>$col1_value))->result_array();

}


查看完整回答
反对 回复 2022-01-24
  • 2 回答
  • 0 关注
  • 169 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号