PHP: search comma separated string in mysql? -
i have mysql query looks mysql find like
strings , displays result.
within same mysql query, have 2 like
.
1 single string , other 1 can single , multiple strings separated commas.
when use code, no results @ though have fields in mysql database , have search strings in columns.
this code:
$area = 'london'; $res = 'santandar, hsbc, rbs, '; $sql = "select * banks location '%$area%' , name '%$res'";
i tried preg_match , didn't return anything:
$sql = "select * banks location '%$area%' , name '".preg_match($res)."'";
if remove second , code looks below, works fine:
sql = "select * banks location '%$area%'";
so issue starts when try search using comma separated string.
could please advise on issue?
edit:
the php varibles posts can in each post.
they so:
$area = $_post['area']; $res = $_post['res'];
you going need blow out separate like
s or
, such as:
...where location '%{$area}' , (name '%{$name1}%' or name '%{$name2}' or ...)
you write php logic:
function build_like_or( $values, $field_name ) { // create array comma-separated values $names = explode( ',', $values ); // trim elements remove whitespaces $names = array_map( 'trim', $names ); // remove empty elements $names = array_filter( $names ); $where = array(); // loop on each, placing "like" clause array foreach( (array)$names $name ) { $where[] = "{$field_name} '%{$name}%'"; } // glue clauses. $where = '(' . implode(' or ', $where) . ')'; // results like: // $where = "(name '%santadar%' or name '%hsbc%')" return $where; }
usage:
$area = 'london'; $res = 'santandar, hsbc, rbs, '; $name_where = build_like_or( $res, 'name'); $sql = "select * banks location '%$area%' , {$name_where}"; // echo $sql outputs "select * banks location 'london' , (name '%santadar%' or name '%hsbc%' or name '%rbs%')
Comments
Post a Comment