Correct PHP method to store special chars in MySQL DB

后端 未结 4 1520
刺人心
刺人心 2020-12-20 19:14

Using PHP, what is the best way to store special characters (like the following) in a MSQUL database, to avoid injections.

« \" \' é à ù

Th

4条回答
  •  借酒劲吻你
    2020-12-20 20:02

    It sounds like your question can be generalised to handling and storing UTF8 with PHP and MySQL.

    To be safe from SQL injections, you should use prepared statements. The mysqli and PDO drivers both support them.

    Prepared statements are automatically quoted by the driver, so you don't need to worry about this.

    Your database tables should be created with the character set utf8 and the utf8_general_ci collation. These my.cnf settings will ensure your MySQL server runs UTF8 all through:

    [mysqld]
    default-character-set=utf8
    default-collation=utf8_general_ci
    character-set-server=utf8
    collation-server=utf8_general_ci
    init-connect='SET NAMES utf8'
    
    [client]
    default-character-set=utf8
    

    Be aware that PHP is generally unaware of UTF-8, so you should take care to use either iconv or mbstring libraries for string handling. See PHPWACT for a good overview.

    Make sure PHP's internal character set is set to unicode

    iconv_set_encoding('internal_encoding', 'UTF-8');
    mb_internal_encoding('UTF-8');
    

    You should also make sure the browser knows the encoding by sending either the correct header or adding a tag for charset.

    That should do it.

提交回复
热议问题