PHP PDO binding variables to a string while concatenating it

∥☆過路亽.° 提交于 2019-12-25 01:46:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!