简体   繁体   English

PHP关键字搜索多个字段填充新输入

[英]PHP Keyword search multiple fields populate new input

I have an HTML input field from which the values are exploded and separated by each space in the string. 我有一个HTML输入字段,该字段的值被分解并由字符串中的每个空格分隔。 This string then searches the database for matches and returns values if there is a match however I would like to search for multiple fields in one table from the original string. 然后,此字符串在数据库中搜索匹配项,如果存在匹配项,则返回值,但是我想从原始字符串的一个表中搜索多个字段。

Hopefully this will clear things up: 希望这会清除一切:

For example if the user searched for 'Sheldon boys jumper' I would like the database to search for a match form each of these keywords in each field of the database eg [school_name], [sex], [product_type]. 例如,如果用户搜索“ Sheldon boys jumper”,我希望数据库在数据库的每个字段(例如[school_name],[sex],[product_type])中搜索这些关键词中的每一个。 At the moment I have this working for one field but I would like to return and gather the values for all three fields. 目前,我正在为一个字段工作,但是我想返回并收集所有三个字段的值。

This is my code: 这是我的代码:

  if (empty($_POST) === false) {
    if(empty($_POST['title']) === true) {
    $no_data = '<div class="alert alert-danger center">Please enter a title</div>';
    } else {        
        $item_title = $_POST['title'];
        $keywords = explode(" ", $item_title);


        $query = "SELECT * FROM products WHERE ";
        foreach($keywords as $keyword) {
            $i++; // dump variable

            if($i == 1) { $query .= "product LIKE '$keyword' "; } 
                   else { $query .= "OR product LIKE '$keyword' "; }
        }
        $query = mysql_query($query);
        $numrows = mysql_num_rows($query);


        $row = mysql_fetch_assoc($query);
        echo $row['product'];
    }
}

You really do want to be using PDO for safety and convenience. 您确实确实想使用PDO来确保安全和方便。 Either way, you still need to prepare a statement. 无论哪种方式,您仍然需要准备一个语句。

$fields = array('fields','you','want','to','search');
foreach($keywords as $keyword) {
    foreach ($fields as $field) {
    $i++; // dump variable
    if($i == 1) {
        $query .= "$field LIKE '$keyword' ";
    } else {
        $query .= "OR $field LIKE '$keyword' ";
    }
}

$i == 1 is weak true. $ i == 1为弱。 You could set $i = false, then if($i === true), saving having to increment the variable for each loop. 您可以设置$ i = false,然后设置if($ i === true),从而不必为每个循环增加变量。 Alternatively, have OR at the end of every line, rather than the start, and the last instance of OR from the final query string. 或者,在每一行的末尾(或不要在开头)使用OR,也不要在最终查询字符串中使用OR的最后一个实例。 This also removes the if from each loop. 这还将从每个循环中删除if。

$fields = array('fields','you','want','to','search');
foreach($keywords as $keyword) {
    foreach ($fields as $field) {
        $query .= "$field LIKE '$keyword' OR ";
    }
}
$query = substr($query, 0, strlen($query) - 4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM