-1

I'm having trouble executing an IN statement for an array. I'm using the IN statement for different companysite types (fk_cs_type). Now my code works when it is a single array eg array("INTERNAL SITE) or array("SUPPLIER") but when there are two elements it doesn't work. Any advice on what I am doing wrong would be appreciated.

$srchField = $srchInput->srchString;
$in = array("INTERNAL SITE","SUPPLIER");    
$type = implode(",", $in);
$dbname = $_SESSION['dbname'];

    try {
        $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     
        $stmt = $conn->prepare('SELECT cs_id, name, alias, fk_cs_type as type, is_active as active FROM companysite WHERE ( fk_cs_type IN (?)) AND (CASE WHEN "'.$isActive.'" = "ALL" THEN is_active = 0 OR 1  ELSE is_active = "'.$isActive.'" END) AND ((CASE WHEN "'.$srchBy.'" = "ALIAS" THEN alias ELSE name END)  LIKE ?)');
        $stmt->bindValue(1, "$type", PDO::PARAM_STR);
        $stmt->bindValue(2, "%$srchField%", PDO::PARAM_STR);
        $stmt->execute(); 
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);            
      }catch(PDOException $e) {         
       $return->error = $e->getMessage();
      }
Ka Tech
  • 8,937
  • 14
  • 53
  • 78
  • Rizier123 I tried both solutions on this page but I get a HY093 invalid parameter number number of bound variables do not match number of tokens. I think it is to do with $stmt->execute($in); Any advice?? – Ka Tech Jun 22 '15 at 12:15

2 Answers2

1

When using an in statement on strings, you still need to encapsulate each string inside the array.

$type = "'".(implode("', '", $in))."'";
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1

I guess it problem with quotes,

Add this code after $in = array("INTERNAL SITE","SUPPLIER"); line,

$in = array_map(function($v){
          return "'$v'";
      }, $in);
viral
  • 3,724
  • 1
  • 18
  • 32