codelove
codelove

Reputation: 2016

MySQL with PHP - LIKE is not working properly

I'd like to search a MySQL database to match keywords passed by the user. I heard that using LIKE is the fastest option but can't find an example of a full simple query using LIKE in PHP code.

This is what I am tring:

$value = 'Fire';
$result = mysql_query("SELECT * FROM effects WHERE title LIKE 'value%'");

I know there is an row in the database with Fire as the title but the query is returning null.

Can someone please give me an example of how to perform a MySQL LIKE search or alternative to find rows by keyword(s).

Thank you.

Upvotes: 0

Views: 332

Answers (2)

Fahim Parkar
Fahim Parkar

Reputation: 31627

You are missing $ before variable value.

Your query should look like

$value = 'Fire';
$result = mysql_query("SELECT * FROM effects WHERE title LIKE '$value%'");

Say there is title like My Fire Effect. You don't want this in search result? If you want to display My Fire Effect in result too then you should use % before $value

$value = 'Fire';
$result = mysql_query("SELECT * FROM effects WHERE title LIKE '%$value%'");

Hope this helps you.

For Differences, see demo with live example

Note, first query in demo returns me 5 rows, however second query returns me 8 rows which is PERFECT.

Upvotes: 2

Yan Berk
Yan Berk

Reputation: 14428

You need to add the dollar sign of the variable:

$result = mysql_query("SELECT * FROM effects WHERE title LIKE '$value%'");

Upvotes: 3

Related Questions