In PHP, you can use the mysqli_real_escape_string function to escape special characters in strings used in mysql. The syntax is "mysqli_real_escape_string(connection,escapestring);".
The operating environment of this tutorial: windows10 system, php5.6. This article is applicable to all brands of computers.
Recommended: "PHP Video Tutorial"
PHP mysqli_real_escape_string() function
Definition and usage
mysqli_real_escape_string() function conversion Defines special characters in strings used in SQL statements.
Syntax
mysqli_real_escape_string(connection,escapestring);
Parameters
connection required. Specifies the MySQL connection to use.
escapestring Required. The string to escape. The encoded characters are NUL (ASCII 0), \n, \r, \, ', " and Control-Z.
Technical Details
Return Value: Returns the escaped string .
PHP Version: 5
Escape special characters in string:
<?php // 假定数据库用户名:root,密码:123456,数据库:RUNOOB $con=mysqli_connect("localhost","root","123456","RUNOOB"); 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 ('$newpers')"); mysqli_close($con); ?>
The above is the detailed content of How to escape special characters in mysql in php. For more information, please follow other related articles on the PHP Chinese website!