1

I want to pass (1,2,3) this to an IN query of where clause. something like this.

$sql = $db->prepare("
    SELECT 
        id, attribution,..........................
    FROM
        filterdaiict
    WHERE Checkbox
        IN (:checkbox)
    HAVING
        distance < :radius
    ORDER BY
        distance ASC
    LIMIT
        0, 50 
");

$sql->bindParam(
    ':checkbox',
    GetCheckboxValue ( $value['CHECKBOXLIST'] ),
    PDO::PARAM_STR 
);

where the function GetCheckboxValue ( $value['CHECKBOXLIST'] ) returns string like 1,2,3. This code does not work. I do not know where the errors could be. Let me know. Thanks in advance.

2 Answers 2

3

This example builds on SamT's answer above to build a query string but still bind the parameters.

// Get your IDs into an array
$ids = explode(',', GetCheckboxValue($value['CHECKBOXLIST']));

// Build a list of placeholders that we can use in the query
$params = array();
foreach ($ids as $idx => $val) {
     $key = ':checkbox' . $idx;
     $params[$key] = $val;
}    

// Join the keys to use as placeholders
$querystr = implode(', ', array_keys($params));

// Prepare our statement using the placeholders we made above
$sql = $db->prepare( " SELECT id, attribution,...... .................... 
    FROM filterdaiict where Checkbox IN ($querystr) 
    HAVING distance < :radius 
    ORDER BY distance ASC LIMIT 0, 50 " );

// Bind a value for each key
foreach ($params as $key => &$val) {
    $sql->bindParam(
        $key,
        $val,      
        PDO::PARAM_STR 
    );
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes you're right with your comment on SamT's answer. Removed my answer.
1

You will have to build they query yourself.

$ids = array(1, 2, 3);
$querystr = implode(',', $ids);

$sql = $db->prepare( " SELECT id, attribution,...... .................... 
    FROM filterdaiict where Checkbox IN ($querystr) 
    HAVING distance < :radius 
    ORDER BY distance ASC LIMIT 0, 50 " );

2 Comments

@papu Do not use this solution, use rather the one given by TheCandyMan.
Do not use the one given by TheCandyMan either, because it will not work. The value will be bound as '1,2,3', which will not match 1, 2 or 3 as intended. This approach will work, but requires sanitisation of the parameters; a better approach is to build the query string dynamically; I'll add an answer below.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.