douqiaotong8682 2014-01-08 21:07
浏览 34

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

I have an HTML input field from which the values are exploded and separated by each space in the string. 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]. 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'];
    }
}
  • 写回答

1条回答 默认 最新

  • dongxiong2000 2014-01-25 20:13
    关注

    You really do want to be using PDO for safety and convenience. 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. You could set $i = false, then if($i === true), saving having to increment the variable for each loop. Alternatively, have OR at the end of every line, rather than the start, and the last instance of OR from the final query string. This also removes the if from each loop.

    $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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序