phpcodeigniterwhere-clausesql-likemysql-error-1054

How to use CodeIgniter's like() with multiple columns?


Here is my selection code from db:

$q = $this->db->like('Autor1' or 'Autor2' or 'Autor3' or 'Autor4', $vyraz)
    ->where('stav', 1)
    ->order_by('id', 'desc')
    ->limit($limit)
    ->offset($offset)
    ->get('knihy');
                    
return $q->result();

Where $vyraz = "Zuzana Šidlíková";

And the error is:

Nastala chyba databázy

Error Number: 1054

Unknown column '1' in 'where clause'

SELECT * FROM (\knihy`) WHERE `stav` = 1 AND `1` LIKE '%Zuzana Šidlíková%' ORDER BY `id` desc LIMIT 9

Filename: C:\wamp\www\artbooks\system\database\DB_driver.php

Line Number: 330

Can you help me solve this problem?


Solution

  • Your syntax is wrong for what you're trying to do, but still technically valid, because this:

    'Autor1' or 'Autor2' or 'Autor3' or 'Autor4'
    

    ...is actually a valid PHP expression which evaluates to TRUE (because all non-empty strings are "truthy"), which when cast to a string or echoed comes out as 1, so the DB class is looking to match on a column called "1".

    Example:

    function like($arg1, $arg2)
    {
        return "WHERE $arg1 LIKE '%$arg2%'";
    }
    
    $vyraz = 'Zuzana Šidlíková';
    echo like('Autor1' or 'Autor2' or 'Autor3' or 'Autor4', $vyraz);
    
    // Output: WHERE 1 LIKE '%Zuzana Šidlíková%'
    

    Anyways, here's what you need:

    $q = $this->db
        ->like('Autor1', $vyraz)
        ->or_like('Autor2', $vyraz)
        ->or_like('Autor3', $vyraz)
        ->or_like('Autor4', $vyraz)
        ->where('stav', 1)
        ->order_by('id', 'desc')
        ->limit($limit)
        ->offset($offset)
        ->get('knihy');