Running multiple queries in model in codeigniter

僤鯓⒐⒋嵵緔 提交于 2019-12-19 03:18:13

问题


I have this code in model in codeigniter:

<?php
Class Mymodel Extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function search($textinput)
    {
        $street = "select street from dataSearch;";
        $stripNameWOSpace = "select stripNameWOSpace FROM dataSearch;";
        $vowels = array('a','e','i','o','u',';','/','-', ' ');
        $string = strtolower($textinput);
        $strippedVowels = mysql_real_escape_string(str_replace($vowels, '', $string));
            $this->db->query("select dataSearch.id,
                dataSearch.name,
                dataSearch.street,
                dataSearch.city,
                dataSearch.lat,
                dataSearch.lng,
                category.asiatype from dataSearch join category on dataSearch.cat = category.id
                where dataSearch.street like '%".$textinput."%'");
            $this->db->query("select dataSearch.id,
                dataSearch.name,
                dataSearch.street,
                dataSearch.city,
                dataSearch.lat,
                dataSearch.lng,
                category.asiatype from dataSearch join category on dataSearch.cat = category.id
                where dataSearch.stripNameWOSpace like '%".$strippedVowels."%'");
            $query = $this->db->get();
            $query->result();

    }
}
?> 

I just want to execute multiple queries. You notice in where statement the two have different condition. I just want to get the result for the two queries. I try the switch statement to execute both queries and it is not working. Help me.


回答1:


You can set the query to a variable to do your things with each query.

Like this:

Class Mymodel Extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function search($textinput) {
        $query1 = $this->db->query("YOUR QUERY");
        $query2 = $this->db->query("YOUR SECOND QUERY");

        $result1 = $query1->result();
        $result2 = $query2->result();

        return array_merge($result1, $result2); // If you want to merge both results
    }
}

In your controller:

$this->load->model('Mymodel');
$searchresult = $this->Mymodel->search($textinput);

For more information, you should read CodeIgniter User Guide - Model




回答2:


I know...old, was looking for something else when I saw something that could be done better. the two select statements are identical except for the where statement. you can use "OR" to combine the two WHERE statements. use "DISTINCT" to avoid duplicate entries. "UNION" should be used if you really want duplicate entries.



来源:https://stackoverflow.com/questions/21869603/running-multiple-queries-in-model-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!