php

php mysql 특수문자 insert ' 싱글쿼트 single quote - addslash

xemaker 2018. 4. 18. 08:59
php mysql 혹은 mariaDB  프로그래밍을 처음 할때 한번쯤 경험하는 것이 바로 싱글쿼트 single quote 에러일 것이다.

쿼리문은 제대로 쓴거 같은데 왜 에러가 나지... 

하고 에러문을 보니

title=adidas Women's Cloudfoam QT Racer w Running Shoe, Clear Onix/White/Clear Onix, 8 M US

Error: INSERT INTO godo_item (srl,cateCd,goodsNm,create_at) VALUES ('B01HSIH68K','001','adidas Women's Cloudfoam QT Racer w Running Shoe, Clear Onix/White/Clear Onix, 8 M US',now())

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's Cloudfoam QT Racer w Running Shoe, Clear Onix/White/Clear Onix, 8 M US',now())' at line 2title=Zhuanglin Women's Quick Drying Aqua Water Shoes

해석을 해보니 's Cloudfoam 근처에서 에러가 난다고 써있다.

원인은 바로 Women's Cloudfoam 이였다.

특히 외국은 Men's Women's 처럼 ' 를 많이 쓴다.

흠.. 저 처리를 해줘야 되는구나..

mybatis 같은 경우는 변수가 통째로 문자열로 취급하여 문제 없으나 php는 변수에 대입하는 방식이라 ' 가 걸린다.

그래서 ' 처리를 해줘야 하는데 escape 하면 된다.

즉, \' 이런식으로..

php에서는 이런걸 해주는 addslash 함수가 있다.

그래서
$title=addslash($title);

했더니 insert가 오류 안나고 잘 되었다.