views:

60

answers:

4

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?

+1  A: 

It probably should be:

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

webdestroya
+1  A: 

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
PHP_Jedi
(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.)
bobince
+7  A: 

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')
Paolo
+1  A: 

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)";
John Kugelman
Thanks to everyone, I will read up on "IN" now.
pg
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.
pg
Careful if you edit the code, `$fruits` starts out as an array and turns into a string after the implode().
John Kugelman