【问题标题】:How to use multiple HTML select tags make an SQL query如何使用多个 HTML 选择标签进行 SQL 查询
【发布时间】:2014-07-08 20:33:50
【问题描述】:

我要做的是创建一个表单,用户从 2 个“选择”标签中选择一个选项,然后选择标签中的值用于 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%' ";
}

【问题讨论】:

  • 您正在连接您的输入变量,然后在space 上展开结果。一个输入的结尾和下一个输入的开头之间很可能没有空格。另请注意,您的代码容易受到 SQL 注入的影响。
  • 您应该在$input$topic$location 之间放置空格,如下所示:$combined = $input . ' ' . $topic . ' ' . $location; 以便正确分解它们:$terms = explode(" ", $combined);
  • MySQL 不是 SQL Server

标签: php html mysql sql sql-server


【解决方案1】:

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

$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%' ";
}

【讨论】:

    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多