search

Home  >  Q&A  >  body text

Correct use of mysqli set_charset()

I have questions about correct usage $mysqli->set_charset(). I haven't used this feature on my website in years. Now I'm rewriting my connection script and want $mysqli->set_charset() to be applied correctly. Currently the site is still based on "latin1" (but I will be switching to UTF-8 (utf8mb4) soon.)

MySQLi on my server (which I manage myself) has been using a latin1 configuration for years. I guess it wouldn't hurt to add this now $mysqli->set_charset("latin1")?

If MySQLi is configured as utf8mb4 by default, will there be strange encoded characters on my website without the $mysqli->set_charset() function?

I want to confirm my hypothesis.

P粉908643611P粉908643611369 days ago406

reply all(1)I'll reply

  • P粉674999420

    P粉6749994202024-01-11 15:16:05

    mysqli::set_charset() Sets the character set of the connection, i.e. "all strings I send over this connection will use this > encoding , I want coding back too”. You need to match this to the encoding you are using on the PHP side.

    That is, even if the current setting is wrong, if you change the current value, it may cause data corruption. This is because in some cases data that is corrupted during transfer from your database to your database will be corrupted in the same way as long as the settings are consistent.

    Before making any changes, you need to determine what encoding is currently used and whether the data in the database is corrupted. From there you can chart a path to ensure that all encodings match, that your data is encoded and processed correctly at all steps, and that existing data is repaired.

    As always, please see the main post: UTF-8 throughout

    Additional Thoughts:

  • Cancelreply