PHP mysqli real_escape_string() 함수
예 - 객체 지향 스타일
문자열의 특수 문자 이스케이프:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " .
$mysqli -> connect_error;
exit();
}
// Escape special characters, if any
$firstname = $mysqli -> real_escape_string($_POST['firstname']);
$lastname = $mysqli -> real_escape_string($_POST['lastname']);
$age =
$mysqli -> real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
$mysqli -> close();
?>
하단의 절차적 스타일의 예를 보십시오.
정의 및 사용
real_escape_string() / mysqli_real_escape_string() 함수는 연결의 현재 문자 집합을 고려하여 SQL 쿼리에서 사용하기 위해 문자열의 특수 문자를 이스케이프합니다.
이 함수는 SQL 문에서 사용할 수 있는 유효한 SQL 문자열을 만드는 데 사용됩니다. 다음 코드가 있다고 가정합니다.
<?php
$lastname = "D'Ore";
$sql="INSERT INTO Persons (LastName) VALUES ('$lastname')";
// This query will fail, cause we didn't escape $lastname
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
?>
통사론
객체 지향 스타일:
$mysqli ->
real_escape_string(escapestring)
절차 스타일:
mysqli_real_escape_string(connection, escapestring)
매개변수 값
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
escapestring | Required. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z. |
기술적 세부 사항
반환 값: | 이스케이프된 문자열을 반환합니다. |
---|---|
PHP 버전: | 5+ |
예 - 절차 스타일
문자열의 특수 문자 이스케이프:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Escape special characters, if any
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con, $sql))
{
printf("%d Row inserted.\n", mysqli_affected_rows($con));
}
mysqli_close($con);
?>
❮ PHP MySQLi 참조