Select case insensitive using mysql, php and pdo

陌路散爱 提交于 2020-01-30 11:40:06

问题


I'm trying to select some data from a mysql table but I cannot get the Where comparison to be case insensitive, I tried using LOWER:

$wildcard = $_GET['q'];
        $query = "SELECT id, name, departamento FROM gestionDoc_cargos WHERE (LOWER(name) LIKE '%' LOWER(:wildcard) '%' OR LOWER(departamento) LIKE '%' LOWER(:wildcard) '%')";

        try{
            $result = DB::getInstance()->prepare($query);
            $result->bindParam(':wildcard', $wildcard, PDO::PARAM_STR);
            $result->execute();
            $result = $result->fetchAll(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            die($e->getMessage());
        }
        print_r($result);
        echo json_encode(array_values($result));

but I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOWER('C') '%' OR LOWER(departamento) LIKE '%' LOWER('C') '%')' at line 1

and if I remove the LOWER from the query I get a case sensitive select.


回答1:


This

...snip... ) LIKE '%' LOWER(:wildcard) '%' OR ...snip

is incorrect. You've got a string ('%') followed by a function call (LOWER()) followed by another string, and they're just sitting there - no connecting logic, no concatenation, blah blah blah .

It should be

... LIKE CONCAT('%', LOWER(:wildcard), '%') OR ...

And by default, mysql comparisons ARE case insensitive, unless you force a binary comparison, or you're using a case sensitive collation on your db/table.



来源:https://stackoverflow.com/questions/30850683/select-case-insensitive-using-mysql-php-and-pdo

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