Hàm mysqli real_escape_string () trong PHP
Ví dụ - Kiểu hướng đối tượng
Thoát các ký tự đặc biệt trong chuỗi:
<?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();
?>
Xem ví dụ về phong cách thủ tục ở phía dưới.
Định nghĩa và Cách sử dụng
Hàm real_escape_string () / mysqli_real_escape_string () thoát các ký tự đặc biệt trong một chuỗi để sử dụng trong truy vấn SQL, có tính đến bộ ký tự hiện tại của kết nối.
Hàm này được sử dụng để tạo một chuỗi SQL hợp pháp có thể được sử dụng trong một câu lệnh SQL. Giả sử chúng ta có mã sau:
<?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);
}
?>
Cú pháp
Phong cách hướng đối tượng:
$mysqli ->
real_escape_string(escapestring)
Phong cách thủ tục:
mysqli_real_escape_string(connection, escapestring)
Giá trị tham số
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. |
Chi tiết kỹ thuật
Giá trị trả lại: | Trả về chuỗi thoát |
---|---|
Phiên bản PHP: | 5+ |
Ví dụ - Phong cách thủ tục
Thoát các ký tự đặc biệt trong chuỗi:
<?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);
?>
❮ Tham khảo PHP MySQLi