PHP mysqli_real_escape_string()Functions
Escape special characters in a string:
<?php
// 假定数据库用户名:root,密码:123456,数据库:EXAMPLE
$con=mysqli_connect("localhost","root","123456","EXAMPLE");
if (mysqli_connect_errno($con))
{
echo "连接 MySQL 失败: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE websites2 LIKE websites");
$newname="Example'教程";
// 没有转义 $newname 中特殊字符,执行失败
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newname')");
// 转义特殊字符
$newpers=mysqli_real_escape_string($con,$newname);
// 转义后插入,执行成功
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newpers')");
mysqli_close($con);
?>
Definition and Usage
The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.
Syntax
mysqli_real_escape_string(connection,escapestring);
| Parameters | Description |
|---|---|
| connection | Required. Specifies the MySQL connection to use. |
| escapestring | Required. The string to be escaped. The encoded characters are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z. |
Technical Details
| Return value: | Returns the escaped string. |
|---|---|
| PHP version: | 5+ |
PHP MySQLi Reference Manual Other Extensions