简体   繁体   中英

Multiple keyword search form using php and mysql

I have created a basic search form that allows a user to search my database by entering a keyword. If their keyword matches, a result is displayed. However, now I am trying to figure out how to search the database when the user enters more than one keyword. For instance, if I want to search by first name I can do so but if I want to search by both first name and last name I can't. I'm not sure how I would take the string that is entered into the form and break it up into two separate strings so that it can be treated as two different strings and then saved into a variable that will check both strings against the database.

 <?php
include("dbconnect.php");

    if(!isset($_POST['search'])) 
 {
     header("Location:index.php");
 }

$search_sql="SELECT * FROM speakers 
WHERE fname LIKE '%".$_POST['search']."%'
    OR lname LIKE '%".$_POST['search']."%'
    OR city LIKE '%".$_POST['search']."%'
    OR state LIKE '%".$_POST['search']."%'
    OR ageGroup LIKE '%".$_POST['search']."%'
    OR topic1 LIKE '%".$_POST['search']."%'
    OR topic2 LIKE '%".$_POST['search']."%'
    OR topic3 LIKE '%".$_POST['search']."%'";

$search_query=mysqli_query($dbc, $search_sql);

if(mysqli_num_rows($search_query) !=0) 
{
     $search_rs=$search_query->fetch_assoc();
}
?>

<p>Speaker Results</p>

<?php 
if(mysqli_num_rows($search_query)!=0) 
{
    do { ?>
            <p>
            <?php 

                echo $search_rs['fname'];
                echo $search_rs['lname'];
                echo $search_rs['city'];
                echo $search_rs['state'];
                echo $search_rs['ageGroup'];
                echo $search_rs['topic1'];
                echo $search_rs['topic2'];
                echo $search_rs['topic3'];
            ?>
            </p>
            <?php   
       } while ($search_rs=$search_query->fetch_assoc());
} 

else 
{
    echo "No results found"; 
} 
?>

You can use regular expression, something like:

SET @keywords = "john|doe";

SELECT * FROM speakers 
WHERE fname REGEXP @keywords
    OR lname REGEXP @keywords
    OR city REGEXP @keywords;

I should note that this kind of querying is not efficient. I would instead look into some PHP search extensions: http://php.net/manual/en/refs.search.php

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