Latest web development tutorials

PHP mysqli_real_escape_string () function

PHP MySQLi Reference Manual PHP MySQLi Reference Manual

Escape special characters in the string:

<?php 
// 假定数据库用户名:root,密码:123456,数据库:w3big 
$con=mysqli_connect("localhost","root","123456","w3big"); 
if (mysqli_connect_errno($con)) 
{ 
    echo "连接 MySQL 失败: " . mysqli_connect_error(); 
} 

mysqli_query($con,"CREATE TABLE websites2 LIKE websites");

$newname="本'教程";

// 没有转义 $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 ('$newname')");

mysqli_close($con);
?>

Definition and Usage

mysqli_real_escape_string () function escapes in SQL statements using the special characters in a string.


grammar

mysqli_real_escape_string( connection,escapestring ) ;

参数 描述
connection 必需。规定要使用的 MySQL 连接。
escapestring 必需。要转义的字符串。编码的字符是 NUL(ASCII 0)、\n、\r、\、'、" 和 Control-Z。

technical details

return value: Returns the escaped string.
PHP version: 5+


PHP MySQLi Reference Manual PHP MySQLi Reference Manual