0

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.

5
  • 'value%' should be '$value%'.. you also need to sanitize user inputs to avoid SQL injections or use PDO prepared statements. Commented Jul 1, 2012 at 6:31
  • ok so this is the new example $value = mysql_real_escape_string('fire'); $result = mysql_query("SELECT * FROM effects WHERE title LIKE '$value%'"); Commented Jul 1, 2012 at 6:37
  • what is PDO? is it better than mysql_real_escape_string() Commented Jul 1, 2012 at 6:38
  • you can read about it here.. that way you can avoid using mysql_* functions. Commented Jul 1, 2012 at 6:42
  • @codelove : Say there is title like "My Fire Effect". You don't want this in search result? Commented Jul 1, 2012 at 7:03

2 Answers 2

3

You need to add the dollar sign of the variable:

$result = mysql_query("SELECT * FROM effects WHERE title LIKE '$value%'");
Sign up to request clarification or add additional context in comments.

6 Comments

This query is not valid. Use Fahim's answer.
@Bailey: I've tweaked the answer. You can do it yourself, too.
@Bailey The original question consisted only of the word 'Fire'.
@Bailey: my edit is waiting for review, you're unable to see it yet.
Still waiting for review? '$value%' isn't valid. It's '%$value%'
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.