'addslashes 함수의 필요성'에 해당되는 글 1건

728x90

addslashes 함수의 필요성

 

addslashes(string str) 함수는 php와 데이터베이스의 연동 db insert,update 시 필수적으로 해줘야 한다.


addslashes 함수는 매개변수로 넘겨준 문자열 안에 single quote(') 혹은 double quote("), 백슬래쉬(\), NULL 바이트가 포함되어 있다면 해당 문자 앞에 역슬래시(\)를 추가해 주는 함수다.

insert into dbtable (text) values (''사랑해'라고 말해줘요'); // DB 입력시 에러 발생

 

$text = addslashes($text);
insert into dbtable (text) values ('\'사랑해\'라고 말해줘요');

insert into dbtable (text) values ('I\'m sorry, I can\'t help you after all.');

 

DB에 있는 걸 읽어와서 Web 브라우저에 뿌려줄 때는 역슬래쉬(\)를 제거하는 함수인 stripslashes()를 사용한다.
검색어를 입력할 때 \\\ 가 많이 생긴다면 이걸 제대로 처리해주지 못해서 생기는 증상이다.

 

post해서 넘어온 변수를 일일이 addslashes해주는 건 귀찮은 일이고 화면에 출력할 때 stripslashes 하는 것도 상당히 귀찮은 일이다.

array_map() 함수를 사용하면 쉽게 해결된다.

post경우
$data = array_map('addslashes', $data);

select경우
while($data=mysql_fetch_array($row)){
 $data=array_map('stripslashes', $data);
}


대체 문법으로 표현하면


while($data=mysql_fetch_array($row)) :
 $data=array_map('stripslashes', $data);

endwhile;


 

블로그 이미지

Link2Me

,