'PHP join'에 해당되는 글 1건

728x90

PHP 에서 검색어를 여러개 입력하여 AND 조건이나 OR 조건을 검색해야 하는 경우가 있다.


검색어가 여러개면 보통 이렇게 검색어 처리를 하기 쉽다.

$keystr = explode(" ", $keyword);

$sqlque .= " and (eng LIKE '%".trim($keystr[0])."%')";


if($keystr[1]) {
    $sqlque .= " and (eng LIKE '%".trim($keystr[1])."%')";
}
if($keystr[2]) {
    $sqlque .= " and (eng LIKE '%".trim($keystr[2])."%')";
}
if($keystr[3]) {
    $sqlque .= " and (eng LIKE '%".trim($keystr[3])."%')";
}
if($keystr[4]) {
    $sqlque .= " and (eng LIKE '%".trim($keystr[4])."%')";
}
if($keystr[5]) {
    $sqlque .= " and (eng LIKE '%".trim($keystr[5])."%')";
}


이걸 좀더 깔끔하기 처리하는 방법은 아래처럼 array 와 join 함수를 이용하는 것이다.

$keystr = explode(" ", $keyword);
$exp_query = array();
for ($i = 0; $i < count($keystr) ; $i++) {
    array_push($exp_query, "eng LIKE '%".$keystr[$i]."%'" );
}
if(count($exp_query) > 0){
    $sqlque .= " and ( ";
    $sqlque .= join(" and ", $exp_query);
    $sqlque .= " ) ";
}
echo $sqlque; // 쿼리문이 정상인지 확인


블로그 이미지

Link2Me

,