How to escape special characters when php accesses mysql data

coldplay.xixi
Release: 2023-03-05 19:50:01
Original
2193 people have browsed it

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
Copy after login

PHP version after 7.0:

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string
Copy after login

Method 2: Use the escape function addslashes()

Suitable for versions PHP4, PHP5, PHP7

addslashes ( string $str ) : string
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!