简体   繁体   中英

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. 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'];
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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