dongpu2694 2015-06-23 07:24
浏览 97

PHP MYSQL在PDO中使用IN()和CASE等

I've been trying to implement an IN statment in my PDO sql. I've succesfully implemented a simple using the solution found in Using PDO with IN

My code is as follows:

        $in_array = array("INTERNAL SITE","SUPPLIER");
        $in  = str_repeat('?,', count($in_array) - 1) . '?';
        $dbname = $_SESSION['dbname'];
        $conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass); 
       //connect to db
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
      //error modes  
        $sql = "SELECT cs_id, name, alias, fk_cs_type as type, is_active as active 
        FROM companysite WHERE ( fk_cs_type IN ($in))";
        $stmt = $conn->prepare($sql);   
        $stmt->execute($in_array); 

However my end goal is to also implement CASE and Like clause referencing an additional 2 variables ($srchBy and $srchField). When I try to do this I get a HY093 error. What am I doing wrong in this code?

        $in_array = array("INTERNAL SITE","SUPPLIER");
        $in  = str_repeat('?,', count($in_array) - 1) . '?';
        $srchBy = "ALIAS";
        $dbname = $_SESSION['dbname'];
        $conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass); 
       //connect to db
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     
       //error modes     
        $sql ="SELECT cs_id, name, alias, fk_cs_type as type, 
               is_active as active FROM companysite
               WHERE ( fk_cs_type IN ($in)) AND 
              ((CASE WHEN $srchBy = 'ALIAS' THEN alias ELSE name END) 
              LIKE $srchField)"; 
        $stmt = $conn->prepare($sql);   
        $stmt->execute($in_array); 
  • 写回答

1条回答 默认 最新

  • doufang7385 2015-06-23 07:51
    关注

    Currently, your final SQL will look something like this:

    SELECT 
        cs_id, 
        name, 
        alias, 
        fk_cs_type as type, 
        is_active as active 
    FROM 
        companysite
    WHERE 
        ( fk_cs_type IN ('INTERNAL SITE','SUPPLIER')) AND 
        ((CASE WHEN 'ALIAS' = 'ALIAS' THEN alias ELSE name END) LIKE 'value_of_$srchField_variable')
    

    Unless you plan turning the statement into a MySQL View, why not consider using php conditionals to build a cleaner, less complex SQL statement.

    $sql = "SELECT cs_id, name, alias, fk_cs_type as type, is_active as active 
            FROM companysite
            WHERE ( fk_cs_type IN ($in) )";
    
    if($srchBy == 'ALIAS') 
    {
        $sql.= " AND alias LIKE $srcField";
    }
    else
    {
        $sql.= " AND name LIKE $srcField";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集