Ryman Holmes
Ryman Holmes

Reputation: 756

PHP MySQL LIKE command not working properly

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.

Upvotes: 1

Views: 1987

Answers (2)

Saravana Kumar
Saravana Kumar

Reputation: 21

$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.

Upvotes: -2

Orangepill
Orangepill

Reputation: 24645

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

Upvotes: 3

Related Questions