如何使用多个HTML选择标记进行SQL查询

时间:2014-07-08 20:33:50

标签: php html mysql sql sql-server

我要做的是创建一个表单,用户从2中选择一个选项'选择'标签,然后select标签的值用于SQL查询(即results.php?select=option1+option2)。我已经设法使其在查询中使用其中一个值,但是我无法获取它以便在查询中使用这两个值。

到目前为止,这是我的代码:

$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location']; //the second select box value which isnt being inserted into the query
$combined = $input . $topic . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";

foreach ($terms as $each){
    $i++;
    if ($i == 1)
        $query .= "keywords LIKE '%$each%' ";
    else
        $query .= "OR keywords LIKE '%$each%' ";
}

1 个答案:

答案 0 :(得分:0)

为什么要合并这些术语然后再将它们分开? :/。没有必要。您还使用"分隔字符串。 "但如果文本之间没有间距,则数组将两个值都作为一个

$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location'];
$terms[]=$input;
$terms[]=$topic;
$terms[]=$location;

$query = "SELECT * FROM search WHERE ";

foreach ($terms as $each){
    if ($each != $terms[count($terms)-1]) //If $each is not the last item in the array
        $query .= "keywords LIKE '%$each%' ";
    else
        $query .= " OR keywords LIKE '%$each%' ";
}