Search code examples
phpcodeigniteractiverecordaliasdisambiguation

CodeIgniter query with a table join and LIKE conditions on multiple tables gives 1052 ambiguous field error


I want to make automatic search, based on article title, to show last news about it. These news can be in one or several tables, we don't know for use. Here it is my code:

$search = 'any article title';
$Linkearray = array('title' => $search);
$Linkearray2 = array('text' => $search);
$this->db->or_like($Linkearray);
$this->db->or_like($Linkearray2);
$this->db->from('table1', 'table2');
$query = $this->db->get();

Then I try to show results on page by next code:

foreach ($query->result_array() as $row):
    echo $row['title'];
endforeach;

The problem is, that it shows search results only from table1. If I rewrite a line of code into:

$this->db->from('table1, table2');

I get an error 1052 because one of the field names in my LIKE condition exists in both tables.


Solution

  • And, here is solution:

    $search = 'some word';
    $Linkearray = array('table1.title' => $search,'table2.text' => $search);
    $Linkearray2 = array('table2.title' => $search,'table2.text' => $search);
    $this->db->or_like($Linkearray);
    $this->db->or_like($Linkearray2);
    $this->db->from('table1,table2');
    $query = $this->db->get();
    
    foreach ($query->result_array() as $row):
    echo $row['title'];
    endforeach;
    

    This way - you will avoid 1052 error, and script will return data from both tables. Query generated in this case is:

    SELECT * 
    FROM (`table1`, `table2`)
    WHERE `table1`.`title` LIKE '%strokes%'
       OR `table2`.`text` LIKE '%strokes%'
       OR `table2`.`title` LIKE '%strokes%'
       OR `table2`.`text` LIKE '%strokes%'
    

    However, it will return some duplicated results... Better query, or php manipulation of results... to get desired output.