2

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.

2 Answers 2

1

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."'))";
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

+1 because this will work, but 32bitfloat's answer using SQL's IN is more readable.
Thanks, it looks like I made a couple of mistakes anyway. Didn't know about IN statements, so I learned something out of this. :)

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.