0

My problem is with binding params. When i dont use any filters (and dont need to bind anything) my code works fine, but when i use parameters in query wont get anything.

I made something like this :

    if(count($nameFilters) > 0){
      $nameParameters = "Name IN (";
      for($i=0; $i<count($nameFilters); $i++){
        $nameParameters .= "name" . $i;
        if($i < count($nameFilters)-1)
          $nameParameters .= ",";
      }
    $nameParameters .= ") ";
    }

$query = "SELECT id, Name, Size, Color FROM " . $this->table_name . " " . $where . " ";

if(count($nameFilters) > 0)
    $query.= $nameParameters;

    $stmt = $this->connection->prepare($query);

if(count($nameFilters) > 0){
    for($i = 0;$i<count($nameFilters);$i++){
    $tmp_string = $nameFilters[$i];
    $tmp_string=htmlspecialchars(strip_tags($tmp_string));
    $tmp_string = "%{$tmp_string}%";
    $stmt->bindParam("name" . $i, $tmp_string);
}
}

My $query value is :

SELECT id, Name, Size, Color FROM shoes 
WHERE Name IN (name0) 
Skeldar
  • 153
  • 13
  • 1
    Possible duplicate of [How to pass an array within a query string?](https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string) – Jason Papp Jan 26 '18 at 21:21
  • Please provide a [mcve] showing what you have tried. – Alan Jan 26 '18 at 21:33

3 Answers3

0

If you change your URL parameters to url?name[]=asd1&name[]=asd2&color[]=red&color[]=blue, PHP will automatically treat $_GET['name'] as an array.

Jason Papp
  • 41
  • 1
  • 7
0

There is a function in PHP that takes care of this for you, its called http_build_query. Take a look at it and how it works.

Ice76
  • 1,143
  • 8
  • 16
0

Ok so i figured answer by searching google for few hrs.

making parameters string to query :

$nameParameters .= ":name" . $i;// i was missing ":" -_-

binding should be :

if(count($nameFilters) > 0){
    for($i = 0;$i<count($nameFilters);$i++){
        $tmp_string = $nameFilters[$i];
        $stmt->bindValue("name" . $i, $tmp_string);
    }
    }
Skeldar
  • 153
  • 13