Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running multiple queries in model in codeigniter

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.

like image 790
user987654321 Avatar asked Feb 19 '14 02:02

user987654321


Video Answer


2 Answers

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

like image 169
Tony Dinh Avatar answered Oct 02 '22 00:10

Tony Dinh


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.

like image 44
SomeOne_1 Avatar answered Oct 01 '22 23:10

SomeOne_1