Current Location: Home> Function Categories> mysql_real_escape_string

mysql_real_escape_string

Escape special characters in strings used in SQL statements.
Name:mysql_real_escape_string
Category:Uncategorized
Programming Language:php
One-line Description:Escape special characters in strings to prevent SQL injection attacks

Function name: mysql_real_escape_string()

Applicable version: PHP 4.3.0 and above, but it is not recommended to use in PHP 7.0.0 and above because this function has been deprecated.

Usage: The mysql_real_escape_string() function is used to escape special characters in a string to prevent SQL injection attacks. This function needs to be used with the MySQL database to escape special characters in the string so that it can be safely inserted into the SQL statement.

Syntax: string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )

parameter:

  • unescaped_string: A string that needs to be escaped.
  • link_identifier (optional): MySQL connection identifier. If this parameter is not provided, the recently opened MySQL connection is used by default.

Return value: Returns the escaped string.

Example:

 // 假设已经建立了与MySQL数据库的连接// 需要转义的字符串$string = "It's a sample string with special characters like ' and \"."; // 转义字符串$escaped_string = mysql_real_escape_string($string); // 执行SQL查询$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_string')"; mysql_query($query);

Notes:

  1. Before using the mysql_real_escape_string() function, a connection to the MySQL database must be established.
  2. To prevent SQL injection attacks, all string parameters should be escaped using the mysql_real_escape_string() function when building SQL query statements.
  3. Since PHP 5.5.0, the mysql_real_escape_string() function has been replaced by the mysqli_real_escape_string() function. For new code, it is recommended to use mysqli or PDO extensions to interact with MySQL databases for improved security and performance.
Similar Functions
Popular Articles