1

I am trying to retrieve data from a table based on if the user enters characters in a search bar which match with a variable that holds the description of an item.

I am doing this using MySQL in PHP and this is the retrieval code I have so far:

$ItemDesc = $_POST['ItemDesc'];

$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";

However I am not getting back the right result, what I am getting back is all the data in the SQL table despite entering unmatching characters all the time.

So e.g. if in the SQL tabel I have one field and the ItemDesc row contains 'Fight', if i enter 'xxx' into the search box and click enter the field will always be retrieved.

SQB
  • 3,926
  • 2
  • 28
  • 49
Ryman Holmes
  • 746
  • 3
  • 22
  • 40

2 Answers2

3

You aren't getting your $ItemDesc variable set so to mysql it's looking like

select * from StockItems where ItemDesc LIKE '%%'

Try to print_r or var_dump the contents of $ItemDesc and the $_POST to see where things are falling down. But it would be a good idea to make sure $ItemDesc meets at least some criteria (min length) before issuing the query

Also sanitize the inputs coming from userland

Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • Doesn't `$ItemDesc = $_POST['ItemDesc'];` set it? – Ryman Holmes May 22 '13 at 17:31
  • it will set it assuming the name on the input that posted it is ItemDesc and the form action is post and the user put information in the field. Lot of ands there... best to just make sure – Orangepill May 22 '13 at 17:34
  • Great, Thanks @Orangepill the problem was my input name was different from the variable. After all it was the html that was wrong :/ – Ryman Holmes May 22 '13 at 17:39
-2
$item = $_POST['itemDesc'];

$result = mysql_query("select * from StockItems where ItemDesc LIKE '%$item%'");

This query is select the result for user assigning character for all places in the itemdesc field.

Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67