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);
?>
❮PHPMySQLiリファレンス