Click to See Complete Forum and Search --> : Search question


tommy1987
02-06-2007, 04:56 AM
I have an array in PHP and am passing it to a function. Now, I want to query the database with all of the keywords in the array to find a match containing all of these keywords at any place in a database column.
I need the SQL all in one statement though, is there something like:
$sql = "SELECT * FROM tbl WHERE col1 like "%word1" AND col1 like "%word2""

etc, the only problem is, it is not known how large this array will be, is there a way to get around this?

If php answer is not known, no problem, please provide some sort of SQL which you think I need and I will try and incorporate it into my database/application.

Thanks very much

russell
02-06-2007, 10:27 AM
http://us3.php.net/manual/en/function.implode.php should help

zackbloom
02-16-2007, 09:35 AM
implode is an option but a foreach offers more options:

$query = 'SELECT * FROM tbl WHERE ';
foreach($array as $k){
$query .= "col1 like '%$k' AND ";
}
$query = substr($query,0,-5); //Remove the last AND

NightShift58
02-16-2007, 09:17 PM
Careful... Change this:$query = 'SELECT * FROM tbl WHERE ';
foreach($array as $k){
$query .= "col1 like '%$k' AND ";
}
$query = substr($query,0,-5); //Remove the last AND to something along these lines:$query = 'SELECT * FROM tbl ';
IF (count($array)) :
$loop_count = count($array);
$query .= " WHERE ";
FOR ($x = 0; $x < $loop_count; $x++) :
$query .= "col1 like '%" . $array[$x] . "' ";
IF ($x < $loop_count) :
$query .= " AND ";
ENDIF;
ENDFOR;
ENDIF;Short of that, you may well end up with a broken script due to an improperly built SQL statement.