I have a database which some of its table columns was in latin1_swedish_ci
, I used PDO connection without charset=utf8
and the data returned well with only using header('Content-Type: application/json; charset=UTF-8');
, then I have created some new table columns with utf8 encoding and when fetching the data it is returned like this ?????
, with some search I found that I have to use PDO connection with charset=utf8
, but adding the last one cause new tables work well, but old tables work wrong, I have used utf8_encoding
but nothing happened, what I have to do now, thanks in advance.
My Answer:
It sounds like you may have a mix of character encodings in your database tables. When you set the charset=utf8 in your PDO connection, it tells MySQL to expect data in UTF-8 encoding. If your old tables were created with latin1_swedish_ci encoding, the data in those tables may not be properly converted to UTF-8 when fetched.
One solution could be to convert the data in your old tables to UTF-8 encoding. You can do this by running a query to convert the character set of the columns in your old tables. Here is an example query to convert a column to UTF-8:
sql
ALTER TABLE your_table MODIFY your_column VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;
Replace `your_table` with the name of your table and `your_column` with the name of the column you want to convert. You may need to run this query for each column in your old tables that needs to be converted.
After converting the character set of your old tables, you should be able to fetch the data properly with the charset=utf8 in your PDO connection.
Alternatively, you could try setting the character set for each query you run using PDO. You can do this by running the following query after establishing your PDO connection:
php
$pdo->exec("SET NAMES 'utf8'");
This will set the character set for the current connection to UTF-8, which may help with fetching data from both old and new tables.
I hope this helps! Let me know if you have any other questions.
Rate this post
3 of 5 based on 6335 votesComments