0

When I replace

$ordering = "apples, bananas, cranberries, grapes";

with

$ordering = "apples, bananas, grapes";

I no longer want cranberries to be returned by my query, which I've written out like this:

$query = "SELECT * from dbname where FruitName LIKE '$ordering'";

Of Course this doesn't work, because I used LIKE wrong. I've read through various manuals that describe how to use LIKE and it doesn't quite make sense to me.

If I change the end of the db to "LIKE "apples"" that works for limiting it to just apples. Do I have to explode the ordering on the ", " or is there a way to do this in the query?

2
  • What does the data look like that you are querying? Can you make an example? Commented May 14, 2010 at 18:13
  • just to help you out, this is a mySQL query called via PHP, not a PHP query. A common mistake though! Commented May 14, 2010 at 18:25

4 Answers 4

8

LIKE is normally used for partially matching strings, e.g. you'd use

WHERE fruitname LIKE 'app%' 

to find 'apple' and 'apples'.

What you (probably) want is the IN clause, e.g.

WHERE fruitname IN ('apples', 'bananas', 'grapes')
Sign up to request clarification or add additional context in comments.

Comments

2

It probably should be:

SELECT * FROM database WHERE FruitName IN ('apples','bananas','grapes')

Comments

2

You need to explode the string and convert it to the appropriate SQL. This is probably the SQL syntax you want to end up with:

SELECT * FROM dbname WHERE FruitName IN ('apples', 'bananas', 'grapes')

PHP code:

$fruits = array();

foreach (explode(', ', $ordering) as $fruit) {
    $fruits[] = "'" . mysql_real_escape_string($fruit) . "'";
}

$fruits = implode(', ', $fruits);
$sql = "SELECT * FROM dbname WHERE FruitName IN ($fruits)";

2 Comments

Wait, when I do this, I get an error message that the [] operator on this line: "$fruits[] = "'" . mysql_real_escape_string($fruit) . "'";" is not supported for strings.
Careful if you edit the code, $fruits starts out as an array and turns into a string after the implode().
2

try using

SELECT * from dbname WHERE FruitName IN ('apples','bananas','grapes')

if you need the result to be in the same order as the IN list extend the query with and ORDER BY

SELECT * from dbname WHERE FruitName IN ('apples','bananas','grapes') ORDER BY FruitName

1 Comment

(Avoid double quotes for SQL string literal delimiters. The ANSI standard delimiter is the single quote; double quotes only work in MySQL, and then only for the default SQL_MODE setting.)

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.