Jump to content

How to search multiple words


Revolutsio

Recommended Posts

I have a got a search bar to look through my database

If I enter  say "Manchester University" in the search bar it only display's "Manchester", How do I make the the code below search multiple words

if (isset($_POST['submit-search'])) {
                    $search = mysqli_real_escape_string($db, $_POST['search']);
                    $sql = "SELECT * FROM games WHERE game LIKE '%$search%'";
                    $result = mysqli_query($db, $sql);
                    $queryResult = mysqli_num_rows($result);

                    if ($queryResult > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {

 

Link to comment
Share on other sites

A google search tells me that you must explode your incoming field with the words on the spaces between them.  Then implode that array with an ' or ' and the field name to be searched.  Then use that string as your where clause value.

Have at it!

Link to comment
Share on other sites

9 hours ago, Barand said:

Can we see the code for your search form?

<form method="POST" action="">
                <input class="search_bar" type="text" name="search" placeholder="Search"/> 
                <button type="submit" name="submit-search">Search</button>
            </form>

 

Link to comment
Share on other sites

what exactly is the "it only display's" and "still just echo's" code that you are describing that is not working?

also, you should use a get method form for searching and determining what data will be gotten and displayed on a page and the form should be 'sticky' so that it remembers what the existing search term is in case the user wants to just modify the search value and try again. doing this will be a necessity if your next step is to combine the search feature with the pagination from your last thread.

Edited by mac_gyver
Link to comment
Share on other sites

44 minutes ago, mac_gyver said:

what exactly is the "it only display's" and "still just echo's" code that you are describing that is not working?

also, you should use a get method form for searching and determining what data will be gotten and displayed on a page and the form should be 'sticky' so that it remembers what the existing search term is in case the user wants to just modify the search value and try again. doing this will be a necessity if your next step is to combine the search feature with the pagination from your last thread.

When I type in the search box above "Manchester University" it only echo's out "Manchester" and I have other fields with the word "Manchester" in so it only shows "Manchester" and not anything if there is a space after the first word.

Link to comment
Share on other sites

3 hours ago, Revolutsio said:

I tried that

Strange!

$pdo->exec("create temporary table games (game varchar(50))");
$pdo->exec("insert into games (game) values
            ('university challenge'),
            ('manchester university zombie apocalypse'),
            ('manchester scenic tours'),
            ('call of duty - manchester university edition')
           ");
           
$search = "manchester_university";                                 // [EDIT]  $search = "manchester university"; GIVES SAME RESULTS as
                                                                   //                   "manchester_university

$res = $pdo->prepare("select game
                      from games
                      where game like ?
                      ");
$res->execute([ "%{$search}%" ]);

foreach ($res as $row) {
    echo $row['game'] . '<br>';
}

outputs

manchester university zombie apocalypse
call of duty - manchester university edition

 

2 hours ago, Revolutsio said:

When I type in the search box above "Manchester University" it only echo's out "Manchester" and I have other fields with the word "Manchester" in so it only shows "Manchester" and not anything if there is a space after the first word.

I would expect that result if you were using something like

<a href="search.php?search=manchester university">Manchester University</a>

but not from a form field

Link to comment
Share on other sites

47 minutes ago, Revolutsio said:

When I type in the search box above "Manchester University" it only echo's out "Manchester" and I have other fields with the word "Manchester" in so it only shows "Manchester" and not anything if there is a space after the first word.

that's because you are searching for %whereeverSPACEsomethingelse% this requires whateverSPACE... to exactly exist somewhere within a column value for a match to occur. did you see @ginerjm's reply above? you will either need to explode the string on the space characters, then dynamically build a term for the where clause for each word, then OR the resulting terms together or alternatively, you can use a full text search.

Link to comment
Share on other sites

Here is a sample from what I learned by doing a google search.  It uses a string that resembles what you are trying to use but a different table structure which I hope is not too difficult for you to modify.

$sch_str = 'manchester university, eton college';	//trim($_POST['search']);
$args = explode(',', $sch_str);
//  start building the where clause value
$where = "'" . trim($args[0]) . "'";
//  finish buildilng the clause
for ($i = 1; $i< count($args);$i++)
	$where .= " or race_winner = '" . trim($words[$i]) . "' ";
$q = "SELECT Season, race_date, race_winner FROM trk_races
		WHERE race_winner = $where";
echo "query is <br>$q<br>";

Note that I have required that your user enters each desired argument to be comma separated.

Link to comment
Share on other sites

Ok in my search bar I am trying to search my database for all the items that have "Sniper Elite" in the database so I type "Sniper Elite" into the search box and click the search button php echo's out the result like

Sniper (should be Sniper Elite)

Sniper (should be Sniper Elite V2 Remastered)

Sniper (should be Sniper Elite III)

Sniper (should be Sniper Elite 5)

How can I make it echo out the full name?

AS the examples are only allowing me to search one word.

<?php
include('includes/config.php');

?>
    <form method="POST" action="">
                <input class="search_bar" type="text" name="search" placeholder="Search"/> 
                <button type="submit" name="submit-search">Search</button>
            </form>

            <?php 
                if (isset($_POST['submit-search'])) {
                    $search = mysqli_real_escape_string($db, $_POST['search']);
                    $sql = "SELECT * FROM games WHERE game LIKE '%$search%'";
                    $result = mysqli_query($db, $sql);
                    $queryResult = mysqli_num_rows($result);

                    if ($queryResult > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            echo "<div>
                                <div>
                                <input type='text' name='game' value={$row['game']} '>
                                </div>
                            </div>
                            ";
                        }
                        

                    } else "There are no results matching your search";
                }
           ?>

 

Link to comment
Share on other sites

BTW - I gave you the general method for solving your issue but don't forget that you should do some alterations to make the query into one that can be prepared.  That would involve (IMHO) using PDO and named args (:val1) to build the where clause and then an array of those args with their associated values before running the query.

Here is what that should resemble:

$sch_str = 'manchester university, eton college';	//trim($_POST['search']);
$args = explode(',', $sch_str);
$parms = array();
//  start building the where clause value
$where = ":val'";
$parms['val0'] = trim($args[0]);
//  finish buildilng the clause
for ($i = 1; $i< count($args);$i++)
{
	$where .= " or race_winner = :val$i";
	$parms["val$i"] = trim($args[$i]);
}
$q = "SELECT Season, race_date, race_winner FROM trk_races
		WHERE race_winner = $where";
echo "query is <br>$q<br>Parms are:<pre>",print_r($parms,true),"</pre>";

This would then be followed by a call to prepare and then a query/execute using PDO

Link to comment
Share on other sites

6 minutes ago, Revolutsio said:

AS the examples are only allowing me to search one word

3 hours ago, mac_gyver said:

what exactly is the "it only display's" and "still just echo's" code that you are describing that is not working?

since you finally posted the code producing the unexpected output, this is because your html markup is broken. you are not surrounding the value = '...' attribute completely/correctly with single-quotes, so the first space character becomes a stop character. in the markup.

  • Great Answer 1
Link to comment
Share on other sites

6 Chrome Extensions to Search for Multiple Words on a Webpage

CTRL + F. Of course, the standard way to find a single word or string of words in an exact order is to simply hit CTRL + F while you're looking at the page you want to search. ...

Multi Search and Multi Jump. ...

Multiple Search and Highlight. ...

efTwo. ...

Isear. ...

Quick Find.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.