我正在尝试使用PHP来遍历搜索词,并在搜索之前将它们附加到SQL字符串上。但是由于此代码,页面无效:
$sql .= "
WHERE Title
LIKE '%$ss[$i]%'";
此代码的完整上下文可以在这里看到:
if(isset($_POST['ss'])){
$ss = $_POST['ss'];
$ss = explode(' ',$ss);
$num_search_terms = count($ss);
$sql = "
SELECT *
FROM CRDRecord";
$i = 0;
while($i <= $num_search_terms){
$ssf=
$sql .= "
WHERE Title
LIKE '%$ss[$i]%'";
$i++;
}
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false){
echo "Error in retrieving row count.";
}
else {
$jsonData = '{ "num":"Number of records-'.$row_count.',<br><br> search terms being used- <br>search 1- '.$ss[0].'<br>search2- '.$ss[1].'<BR>Number of search terms detected- '.$num_search_terms.'<br>SQL STRING: '.$sql.'" }';
echo $jsonData;
}
}
我知道我想要做什么,但无法弄清楚如何表达它。非常感谢任何帮助。
答案 0 :(得分:1)
您需要将WHERE移出LOOP并添加默认条件来处理串联
$sql = "
SELECT *
FROM CRDRecord WHERE 1=1 ";
$i = 0;
while($i <= $num_search_terms){
$ssf=
$sql .= "
AND Title LIKE '%$ss[$i]%'";
$i++;
}
这样做会导致WHERE语句太多,只允许一个。 WHERE 1 = 1是一种允许在开始附加其他条件之前在WHERE子句中具有单个条件的方法。