问题
I'm trying to create an SQL statement which looks something like this:
SELECT * FROM `table` WHERE `attribute` LIKE %variable_1% AND `attribute` LIKE %variable_2% AND ... AND `attribute` LIKE %variable_n%
I have the variables : variable_1, variable_2, ... ,variable_n stored in an array and in order to create the statement mentioned above I'm gonna use a foreach loop, like so:
$sql = 'SELECT * FROM `table` WHERE ';
$variables_array; // this array will contain all the variables mentioned above, the variables are numerically indexed
$total_variables = count($variables_array);
foreach($variables_array as $key => $value){
$sql .= '`attribute` LIKE "%'.$value.'%" ';
if($key != ($total_variables - 1) ){
$sql .= ' AND ';
}
}
My question is, how do I use the 'prepare' and 'bindValue' methods of the PDO and PDO statement object respectively, inside my foreach loop so that each newly inserted variable is both safe to use like they are when they are passed to the 'prepare' method, and than inserted into the statement using 'bindValue'. Or are there some other methods that I need to use for this?
来源:https://stackoverflow.com/questions/16109827/php-pdo-binding-variables-to-a-string-while-concatenating-it