Home >Backend Development >PHP Problem >How to escape special characters when php accesses mysql data

How to escape special characters when php accesses mysql data

coldplay.xixi
coldplay.xixiOriginal
2020-09-07 11:31:522275browse

How to escape special characters when PHP accesses mysql data: You can use the mysql library function to escape, the code is [mysql_escape_string(string $unescaped_string): string]. You can also use the escape function addslashes to escape.

How to escape special characters when php accesses mysql data

[Related learning recommendations: php programming (video)]

How to escape special characters when php accesses mysql data:

Method 1: Using mysql library functions

PHP version before 7.0:

mysql_escape_string ( string $unescaped_string ) : string

PHP version after 7.0:

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string

Method 2: Use the escape function addslashes()

Suitable for versions PHP4, PHP5, PHP7

addslashes ( string $str ) : string

Before PHP 5.4, the PHP command magic_quotes_gpc was on by default. In fact, all GET, POST and COOKIE data are used by addslashes(). Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping.

When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it. That is, when get_magic_quotes_gpc() returns false, use addslashes() to escape special characters. Examples are as follows:

function myaddslashes($data)
{
    if(false == get_magic_quotes_gpc())
    {
        return addslashes($data);//未启用魔术引用时,转义特殊字符
    }
    return $data;
}

If you want to learn more about programming, please pay attention to the php training column!

The above is the detailed content of How to escape special characters when php accesses mysql data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn