Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have a PHP array: Array(keyword1,blah0,blah1,blah2) and an SQL query.

In the query I want to find if one of the data in Array exists in one of the few columns selected (columnA|columnB|columnC) and fetch that row if true.

share|improve this question

You'll need a query like this:

$instring = implode("','", $array);
$sql = "SELECT `xy` FROM `z` WHERE (`columnA` IN ('".$instring."')
OR `columnB` IN ('".$instring."')
OR `columnC` IN ('".$instring."'))";
share|improve this answer

I think this is what you want. I couldn't tell if you wanted to check every column for every value in your array.

SELECT * FROM tableName
WHERE columnA = $phpArray[0] OR
columnA = $phpArray[0] OR
columnB = $phpArray[0] OR
columnC = $phpArray[0] OR
columnA = $phpArray[1] OR
columnB = $phpArray[1] OR
columnC = $phpArray[1] OR
columnA = $phpArray[2] OR
columnB = $phpArray[2] OR
columnC = $phpArray[2] OR 
... 
columnC = $phpArray[n];

You can use PHP to create this statement in a loop

$sql = "SELECT * FROM tableName WHERE ";
for($i=0;$i<count(phpArray)-1;$i++){
   $sql .= "columnA = "+"'"+$phpArray[$i]+"'"+ OR "
   $sql .= "columnB = +"'"+$phpArray[$i]+"'"+ OR "
   $sql .= "columnC = +"'"+$phpArray[$i]+"'"+ OR "
}
$sql .= "columnA = +"'"+$phpArray[$i]+"'"+ OR "
$sql .= "columnB = +"'"+$phpArray[$i]+"'"+ OR "
$sql .= "columnC = +"'"+$phpArray[$i]+"'"+;"
*send sql query

edit: Fixed errors in code

share|improve this answer
    
+1 because this will work, but 32bitfloat's answer using SQL's IN is more readable. – octern Jul 12 '12 at 20:11
1  
Thanks, it looks like I made a couple of mistakes anyway. Didn't know about IN statements, so I learned something out of this. :) – StoicJester Jul 13 '12 at 19:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.