2

I have this code:

$Array=array();
array_push($Array,"Email1","Email2");
$Array=implode("','",$Array);
$Array="'$Array'";
echo "$Array" //Will output 'Email1','Email2'
$Check=$connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN(:Array)");
$Check->execute(array(
    ':Array' => $Array,
));

This query won't work but if I write:

$Check=$connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN('Email1','Email2')");
$Check->execute(array(
    ':Array' => $Array,
));

This works, but I won't bind the array to avoid SQL Injection. How can I fix it?

1
  • comma seperated values isn't good design. consider normalizing your database Commented Dec 31, 2017 at 14:36

1 Answer 1

1

You don't want to bind the imploded list as one element but rather each of the values individually using ? so the end of the statement would be WHERE EMAIL IN (?,?):

$values  = ["Email1","Email2"];
# This should give you ?,?
$bindstr = implode(",",array_fill(0,count($values),'?'));
$query = $connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN({$bindstr})");
# Use the raw values individually in the execute
$query->execute($values);

Hopefully that should get results back you are looking for.

Sign up to request clarification or add additional context in comments.

8 Comments

thanks a lot for your help, could you please exaplain me why in the first row you used the [...],and why did you add in the IN CLAUSE the {..}.Anyway thanks for your help, hope that you'll have a nice day:)
Oh, sorry, the [ and ] in newer versions of php is same as using array() so [ = array( and ] = ).
Thanks for have clarified :)
The {} inside the string sort of enforces that you are using a variable inside those braces. I could have not used the braces, but it's better to use them. It's for complex strings: php.net/manual/en/…
I can't understand a thing how did you bind the values?Is this query 100% secure against sql injection?Thanks for read, and sorry for another nuisance.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.