1

I'm trying to SELECT from an array inside a mysql query

result = mysql_query("
SELECT * FROM fruit_db
WHERE fruit='".$url."'
")

$url has been created by $_GET and exploded into an array. It can be 'apple' or 'apple,banana,orange' for example. Not sure whether to implode back into string or not.

I need to be selecting 'apple' OR 'banana' OR 'orange', not 'apple,banana,orange'.

I'm used to counting the elements of the string, and looping through them, but not inside a mysql query, I can't work out if there's a simple way. I've tried something like

/*    
    result = mysql_query("
    SELECT * FROM fruit_db
    WHERE fruit='".$url[0]."'
    OR  fruit='".$url[1]."'
    // etc
    ")
*/

but I don't know how many elements there will be

2
  • 3
    You should use IN. And you should not use myqsl_* functions anymore. Commented Aug 13, 2013 at 11:29
  • I was going to say use the IN operator Commented Aug 13, 2013 at 11:32

4 Answers 4

5

Try with IN with implode of the array $url like

$sql = "SELECT * FROM fruit_db WHERE fruit IN (".implode(',',$url).")";

Make sure that $url is an array.

And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.

There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

Sign up to request clarification or add additional context in comments.

3 Comments

Will do. once it is all working I will replace the deprecated syntax, thanks. Do I simply replace 'mysql_query' with 'MySQLi' or 'PDO_MySQL'? And do they return the same type of resource?
Yes ,May need some extra config for connection setup in mysqli_* and you can follow the using php.net/manual/en/book.mysqli.php
Again, you beat me to it
2
"SELECT * FROM fruit_db WHERE fruit IN ('".implode("','", $url)."')";

Suppose your $url = array('apple','banana','orange');

Then sql will be :

SELECT * FROM fruit_db WHERE fruit IN ('apple','banana','orange')

Comments

0

you may use

SELECT column_name FROM table_name WHERE column_name IN ("1","2");

Comments

0

Try this

$url=explode(",",$_GET['fruit']);

foreach($url as $fr){
  $result = mysql_query("
  SELECT * FROM fruit_db
  WHERE fruit='".$fr."'
  ")
}

1 Comment

This is kind of what I had before, can whoever down-voted explain why it's bad?

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.