PHP에서 mysqli_real_escape_string() 함수를 사용하는 방법은 무엇입니까?

醉折花枝作酒筹
풀어 주다: 2023-03-10 11:18:01
앞으로
3942명이 탐색했습니다.

이 글에서는 PHP에서 mysqli_real_escape_string() 함수를 사용하는 방법을 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

PHP에서 mysqli_real_escape_string() 함수를 사용하는 방법은 무엇입니까?

mysqli_real_escape_string() 함수는 SQL 쿼리에 사용하기 위해 모든 특수 문자를 이스케이프하는 데 사용되는 PHP의 내장 함수입니다. 쿼리 작업을 방해할 수 있는 특수 문자를 제거하므로 데이터베이스에 문자열을 삽입하기 전에 이를 사용하십시오.

간단한 문자열을 사용하는 경우 백슬래시 및 아포스트로피와 같은 특수 문자가 포함될 수 있습니다(특히 해당 데이터가 입력된 양식에서 직접 데이터를 가져오는 경우). 이는 쿼리 문자열의 일부로 간주되어 올바른 기능을 방해합니다.

<?php
  
$connection = mysqli_connect(
     "localhost" , "root" , "" , "Persons" ); 
         
// Check connection 
if (mysqli_connect_errno()) { 
     echo "Database connection failed." ; 
} 
   
$firstname = "Robert&#39;O" ;
$lastname = "O&#39;Connell" ;
   
$sql ="INSERT INTO Persons (FirstName, LastName) 
             VALUES ( &#39;$firstname&#39; , &#39;$lastname&#39; )";
   
   
if (mysqli_query( $connection , $sql )) {
      
     // Print the number of rows inserted in
     // the table, if insertion is successful
     printf( "%d row inserted.n" , $mysqli ->affected_rows);
}
else {
      
     // Query fails because the apostrophe in 
     // the string interferes with the query
     printf( "An error occurred!" );
}
   
?>
로그인 후 복사

위 코드에서는 mysqli_query()를 사용하여 아포스트로피를 수행할 때 아포스트로피를 쿼리의 일부로 간주하기 때문에 쿼리가 실패합니다. 해결책은 쿼리에서 문자열을 사용하기 전에 mysqli_real_escape_string()을 사용하는 것입니다.

<?php
   
$connection = mysqli_connect(
         "localhost" , "root" , "" , "Persons" ); 
  
// Check connection 
if (mysqli_connect_errno()) { 
     echo "Database connection failed." ; 
} 
       
$firstname = "Robert&#39;O" ;
$lastname = "O&#39;Connell" ;
   
// Remove the special characters from the
// string using mysqli_real_escape_string
   
$lastname_escape = mysqli_real_escape_string(
                     $connection , $lastname );
                      
$firstname_escape = mysqli_real_escape_string(
                     $connection , $firstname );
   
$sql ="INSERT INTO Persons (FirstName, LastName)
             VALUES ( &#39;$firstname&#39; , &#39;$lastname&#39; )";
  
if (mysqli_query( $connection , $sql )) {
      
     // Print the number of rows inserted in
     // the table, if insertion is successful
     printf( "%d row inserted.n" , $mysqli ->affected_rows);
}
   
?>
로그인 후 복사

출력은 다음과 같습니다.

1 row inserted.
로그인 후 복사

위 내용은 PHP에서 mysqli_real_escape_string() 함수를 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!