Попробуйте построить часть выражения LIKE
подготовленного оператора SQL, используя implode
.Затем создайте аргументы параметров для запуска с call_user_func_array()
.
$terms = explode(",", str_replace(",", " ,", $_POST['txtD']));
// PREPARED STATEMENT BUILD
$likes = [];
foreach($terms as $t) {
$likes[] = "col3 LIKE CONCAT('%', ?, '%')";
}
$expr = implode(" or ", $likes);
$sql = "select col1, col2, col3 from tbl ".
"where col1=? and col2 between ? and ? and (". $expr .")";
// PARAM ARG BUILD
$type = 'iii' . str_repeat("s", count($terms));
$sql_params = array_merge(array($stmt, $type, $param1, $param2, $param3), $terms);
// PREPARE AND EXECUTE QUERY
$stmt = mysqli_prepare($con, $sql);
call_user_func_array('mysqli_stmt_bind_param', sql_params);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
SQL и демонстрация построения параметров
В качестве альтернативы,рассмотрим REGEXP
MySQL для выражения регулярного выражения, использующего каналы для обозначения логики OR
:
// REPACE COMMAS BY PIPE
$terms = str_replace(",", "|", str_replace(",", " ,", $_POST['txtD']));
$sql = "select col1, col2, col3 from tbl " .
"where col1=? and col2 between ? and ? and col3 regexp ?";
// PREPARE AND EXECUTE QUERY
$stmt = mysqli_prepare($con);
mysqli_stmt_bind_param($stmt, "iii", $param1, $param2, $param3, $terms);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Обратите внимание, что здесь REGEXP
медленнее, чем эквивалент LIKE
выражение.