Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP将条件附加到准备好的语句中_Php_Mysqli_Prepared Statement - Fatal编程技术网

PHP将条件附加到准备好的语句中

PHP将条件附加到准备好的语句中,php,mysqli,prepared-statement,Php,Mysqli,Prepared Statement,我试图使用一个准备好的语句来搜索一个数据库,我不知道需要搜索多少个参数。因此,下面的示例检查列“title”是否包含两个变量 $stmt = $con->prepare("SELECT title FROM news WHERE title LIKE %?% AND title LIKE %?%"); 如果我想检查第三个变量呢。我可以附加到准备好的语句中吗? 到目前为止,我唯一的解决方案是如下,这是可怕的,因为我不知道变量的最大数量 $no_of_variables = 3; if($

我试图使用一个准备好的语句来搜索一个数据库,我不知道需要搜索多少个参数。因此,下面的示例检查列“title”是否包含两个变量

$stmt = $con->prepare("SELECT title FROM news WHERE title LIKE %?% AND title LIKE %?%");
如果我想检查第三个变量呢。我可以附加到准备好的语句中吗? 到目前为止,我唯一的解决方案是如下,这是可怕的,因为我不知道变量的最大数量

$no_of_variables = 3;

if($no_of_variables == 1){
    $stmt = $con->prepare("SELECT title FROM news WHERE title LIKE %?%");
} else if($no_of_variables == 2){
    $stmt = $con->prepare("SELECT title FROM news WHERE title LIKE %?% AND title LIKE %?%");
} else if($no_of_variables == 3){
    //etc
}

如果可能的话,我会很感激有一个更好的方法来使用准备好的声明。谢谢

通过重复条件
$no\u of_variables
-次来构造准备好的语句:

$where = implode(" AND ", array_fill(0, $no_of_variables, "title LIKE %?%"));
$stmt = $con->prepare("SELECT title FROM news WHERE {$where}");

对于准备好的语句-您应该使用
LIKE?
并将
%
添加到绑定值中(或在MySQL中使用字符串连接),您可以使用分隔符创建参数字符串,然后使用运算符中的
将其传递到查询。我认为您的LIKE子句已损坏。