Reputation:
How to search multiple fields in a MySQL database with a PHP array.
For example, search fields like place_name, admin_name1, and admin_name2 using an array of ["Cambridge","Massachusetts","US"]
with using the wildcard %
Below is the exact structure of database
Upvotes: 2
Views: 111
Reputation: 7240
Imagining your array index names are the same as your table column names:
$query = "select * from tableName";
$arrCount = count($arrName);
$i=1;
if($arrCount) > 0){
$query .= " where";
foreach($arrName as $key->$val){
$query .= $key." LIKE '%".$val."%'";
if($i <= $arrCount)
$query .= " AND";
$i++;
}
}
Then run the query!
Upvotes: 1
Reputation: 475
Try this
$fields = array("place_name", "admin_name1", "admin_name2");
$kwd = array("Cambridge","Massachusetts","US");
$condition = array();
$n = 0;
foreach($fields as $field){
$condition[] .= $field." LIKE '%".$kwd[$n]."%'";
$n++;
}
$condition = implode(" AND ", $condition);
echo $qry = "SELECT * FROM `table` WHERE ( ".$condition." )";
Upvotes: 0
Reputation: 1441
$array = ["Cambridge","Massachusetts","US"];
$list = implode(",", $array);
Then select:
... WHERE place_name IN($list) OR admin_name1 IN($list) OR admin_name2 IN($list)
Upvotes: 0