0

I'm having a bit of difficulty using the values in a PHP array for a mysql function.

I have an array,

$a[0] = 89
$a[1] = 23
$a[2] = 15
$a[3] = 28
$a[4] = ...

And I need to generate a string like so:

$result_array = 'ID = 89 OR ID = 23 OR ID = 15 OR ID = 28 OR ID = ...';

To fetch values from my DB:

$result_test = mysql_query("SELECT * FROM Events Where $result_array");

But I do not know how to create the string $result_array from the array $a.

2 Answers 2

5
$result_test = mysql_query("SELECT * FROM Events Where ID in (".implode(',' , $a).")");

Use the IN operator and send the list as 89,23,15,28 etc

So the query will become ID in (89,23,15,28)

9
  • geez! 14 secs!! arg! you wrote $a instead of $result_array I should give you a big -1 :P Commented Jun 14, 2011 at 22:47
  • pick this because it was waay faster (14 sec) Commented Jun 14, 2011 at 22:59
  • how I can't give you another +1 there Commented Jun 14, 2011 at 23:03
  • @yes123: No, because the source array is $a. $result_array is the name of the intermediate string in the OP's hypothetical solution, which did not get used in this answer. Commented Jun 14, 2011 at 23:13
  • @Tomalak we sorted it out, yes123 and I were just having a little fun :) Commented Jun 14, 2011 at 23:15
1
$result_test = mysql_query("SELECT * FROM Events Where ID IN (".implode(',',$a).')');
2
  • 1
    actually $result_array is the string he is trying to form, so i used the $a array directly :) Commented Jun 14, 2011 at 22:49
  • oh my. Very late here need to sleep. +1 to your answer and comment Commented Jun 14, 2011 at 22:53

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.