I have use inputted values in a variable in this format:
ny,nj,ct
and stored in this variable:
$search_crit
I then run the following
$list = explode(',', $search_crit);
array_map(array($dbh, 'quote'), $list);
$sql1 = sprintf('SELECT `Provider Number`,`Number of Cases` FROM `mytable` where`color` = :colorpicked and `State` in (%s) group by `Provider Number`', implode(',', $list));
$stmt = $dbh->prepare($sql1);
$stmt->bindParam(':color', $colorSel, PDO::PARAM_STR);
$stmt->execute();
$result1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
This works fine when I do a different query where instead of states, they are inputting zip codes, so I end up with something like this: and 'zipcode' in (45040,45249)
. This works fine because they are numbers (I guess).
Back to my code above...if I try this with states like this: and 'states' in (ny,nj,ct)
I get errors saying that ny
isn't a column. If I can somehow run the query like this, it works: and 'states' in ('ny','nj','ct')
.
What's the best approach here? Is there a simple way to insert the single quotes in PHP? Should I change the query to be able to accept a list (ny,nj,ct
) of states that could be any number (e.g., 3 states or 15 states)?
Thanks to @Ryan_W4588 for pointing me in the right direction to prepare the variable. I had to change my PHP code a bit as well to accommodate this.
$list = explode(',', $search_crit);
$newList = "'" .implode("','",$list) ."'";
$sql1 = "SELECT `Provider Number`,`Number of Cases` FROM `mytable` where`color` = :colorpicked and `State` in ({$newList}) group by `Provider Number`";
$stmt = $dbh->prepare($sql1);
$stmt->bindParam(':color', $colorSel, PDO::PARAM_STR);
$stmt->execute();
$result1 = $stmt->fetchAll(PDO::FETCH_ASSOC);