MySQL Escape: Prevent SQL Injection
In MySQL, you can use the mysql_real_escape_string() function to escape strings and prevent SQL injection attacks. This function escapes special characters (such as single quotes, double quotes, backslashes, etc) so that they can be correctly recognized in SQL statements without being misunderstood as part of the SQL statement. Here is a simple example:
<?php
// 连接到数据库
$link = mysql_connect('localhost', 'root', 'password');
mysql_select_db('my_database', $link);
// 需要转义的字符串
$string = "It's a test";
// 进行转义
$escaped_string = mysql_real_escape_string($string);
// 构建SQL查询语句
$query = "INSERT INTO my_table (my_column) VALUES ('$escaped_string')";
// 执行查询
mysql_query($query, $link);
// 关闭数据库连接
mysql_close($link);
?>
In the example above, the mysql_real_escape_string() function is used to escape the string “It’s a test” before inserting it into the database. This prevents SQL syntax errors or SQL injection attacks. It is recommended to use mysql_real_escape_string() when building SQL statements with user input data.