MySQL에 삽입 할 때 PHP에서 작은 따옴표를 이스케이프 처리
이 질문에는 이미 답변이 있습니다.
- PHP에서 SQL 삽입을 어떻게 방지 할 수 있습니까? 답변 28 개
이해할 수없는 복잡한 문제가 있습니다 ...
두 개의 SQL 문이 있습니다.
- 첫 번째는 양식의 정보를 데이터베이스에 입력합니다.
- 두 번째는 위에서 입력 한 데이터베이스에서 데이터를 가져 와서 이메일을 보낸 다음 거래 세부 정보를 기록합니다.
문제는 작은 따옴표가 두 번째 항목에서만 MySQL 오류를 유발하는 것 같습니다! 첫 번째 인스턴스는 문제없이 작동하지만 두 번째 인스턴스는을 트리거합니다 mysql_error()
.
양식의 데이터가 양식에 캡처 된 데이터와 다르게 처리됩니까?
쿼리 1-문제없이 (작은 따옴표를 이스케이프하지 않고) 작동합니다
$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");
쿼리 2-작은 따옴표로 이름을 입력하면 실패합니다 (예 : O'Brien )
$query = mysql_query("INSERT INTO message_log
(order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
VALUES
('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");
이 각 문자열 (둘 다 스 니펫)을 이스케이프 처리해야합니다 mysql_real_escape_string()
.
http://us3.php.net/mysql-real-escape-string
두 쿼리가 다르게 작동하는 이유는 magic_quotes_gpc
켜져 있기 때문일 수 있습니다 (잘못 알고 있어야 함). 이는 $ _GET, $ _POST 및 $ _COOKIES에서 수집 한 문자열이 이스케이프되었음을 의미합니다 (예 :) "O'Brien" -> "O\'Brien"
.
데이터를 저장 한 후 다시 검색하면 데이터베이스에서 다시 가져온 문자열이 자동으로 이스케이프 되지 않습니다 . 당신은 돌아올 "O'Brien"
것이다. 따라서 통과해야합니다 mysql_real_escape_string()
.
2015 년에이 솔루션을 찾고 앞으로 나아가는 사람이라면 ...
이 mysql_real_escape_string()
기능은 PHP 5.5.0부터 더 이상 사용되지 않습니다.
참조 : php.net
경고
이 확장은 PHP 5.5.0부터 더 이상 사용되지 않으며 향후 제거 될 예정입니다. 대신, MySQLi 또는 PDO_MySQL 확장을 사용해야합니다. 자세한 정보는 MySQL : API 안내서 및 관련 FAQ 선택을 참조하십시오. 이 기능의 대안은 다음과 같습니다.
mysqli_real_escape_string()
PDO::quote()
당신은 당신의 끈에서 싸우는 몇 가지가 있습니다.
- 올바른 MySQL 인용 부족 (
mysql_real_escape_string()
) - 잠재적 인 자동 '마법 인용구'-gpc_magic_quotes 설정 확인
- 내장 문자열 변수. PHP가 변수를 올바르게 찾는 방법을 알아야 함
작은 따옴표로 묶은 값이 첫 번째 쿼리의 매개 변수에 없을 수도 있습니다. 귀하의 예는 결국 올바른 이름이며 두 번째 쿼리 만 이름을 다루는 것 같습니다.
PHP와 MySQL을 모두 벗어나는 다음을 수행 할 수 있습니다.
<?
$text = '<a href="javascript:window.open(\\\'http://www.google.com\\\');"></a>';
?>
이것은 MySQL을 다음과 같이 반영합니다.
<a href="javascript:window.open('http://www.google.com');"></a>
어떻게 작동합니까?
우리는 PHP와 MySQL 아포스트로피를 백 슬래시와 아포스트로피로 이스케이프 처리 할 수 있다는 것을 알고 있습니다.
\'
우리는 PHP를 사용하여 MySQL에 삽입하기 때문에 여전히 백 슬래시를 MySQL에 작성하여 이스케이프 처리 할 수 있도록 PHP가 필요합니다. 그래서 우리는 이것을 달성하기 위해 backslash-backslash의 PHP escape 문자를 backslash-apostrophe와 함께 사용합니다.
\\\'
디버깅을 돕기 위해 이와 같은 작업을 수행해야합니다.
$sql = "insert into blah values ('$myVar')";
echo $sql;
작은 따옴표는 작업 쿼리에서 백 슬래시로 이스케이프 처리 된 것을 알 수 있습니다. 이것은 magic_quotes_gpc 설정을 통해 PHP에 의해 자동으로 수행되었거나 코드의 다른 부분에서 직접 수행했을 수도 있습니다 (addslashes 및 stripslashes는 찾는 기능 일 수 있습니다).
참조 매직 지수를
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val
is the data which is troubling you.
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
http://phptutorial.co.in/php-echo-print/
I had the same problem and I solved it like this:
$text = str_replace("'", "\'", $YourContent);
There is probably a better way to do this, but it worked for me and it should work for you too.
참고URL : https://stackoverflow.com/questions/2687866/escaping-single-quote-in-php-when-inserting-into-mysql
'Programing' 카테고리의 다른 글
“객체 참조가 객체의 인스턴스로 설정되지 않았다”는 것은 무엇을 의미합니까? (0) | 2020.05.21 |
---|---|
Haskell에서`data`와`newtype`의 차이점 (0) | 2020.05.21 |
텍스트 뷰에 맞게 텍스트 글꼴 크기를 조정하는 방법 (0) | 2020.05.21 |
자바 생성자 상속 (0) | 2020.05.21 |
올바른 / 올바른 패키지 __init__.py 파일을 작성하는 방법 (0) | 2020.05.21 |