转义字符串中的特殊字符:
<?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);
?>
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!