-1

I am building an inventory system for work, I have a search system to search the database already. But when I search for an item with any spaces in the name it doesnt find any results. Here is my script, any help would be appreciated.

    <?php
    // we connect to our Database
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("inventory") or die(mysql_error());

    $find = $_POST['find'];

    echo "<h2>Search Results:</h2><p>";
    //If they did not enter a search term we give them an error
    if ($find == "")
    {
    echo "<p>You forgot to enter a search term!";
    exit;
    }

    // We perform a bit of filtering
    $find = strtoupper($find);
    $find = strip_tags($find);
    $find = trim ($find);

    //Now we search for our search term, in the field the user specified
    $data = mysql_query("SELECT * FROM parts WHERE vendor LIKE'%$find%' OR category
    LIKE'%$find%' OR prtid LIKE'%$find%' OR description LIKE '%$find%'");
    if (!$data) { // add this check.
    die('Invalid query: ' . mysql_error());
}
  • 1
    what would be a search term that fails on what searched for text? –  Jul 17 '12 at 20:36
  • Why are you trimming it then? -edit- oh, nm - not finding any spaces? I'd say posted text is encoded, and you need to url decode the parm values. – Tim Jul 17 '12 at 20:37
  • make sure to use mysql_real_escape_string in your query http://www.php.net/manual/en/function.mysql-real-escape-string.php – Horen Jul 17 '12 at 20:37
  • If I search for a part number like 420 99 4710 00 04 which is identical to the part number in the database then the result shows that is isnt in my database! – user1532928 Jul 17 '12 at 20:42

2 Answers2

1

% will only insert wildcards on the outside of the search text as a whole. You will need to write a more complex query if you want to handle multiple-word search strings.

keaton_fu
  • 444
  • 2
  • 9
0
$searchTerms = explode(' ', $find);
$searchTermBits = array();
foreach ($searchTerms as $term) {
    $term = trim($term);
    if (!empty($term)) {
        $searchTermBits[] = "vendor LIKE '%$term%'";
    }
}

then in query just implode the $searchTermBits instead of $term

Vinit
  • 1,815
  • 17
  • 38