메뉴 건너뛰기

프로그램언어

2015.04.14 19:27

검색어 처리 루틴

조회 수 20778 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

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; // 쿼리문이 정상인지 확인


하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved