J
J
Jan2018-01-23 12:45:08
PHP
Jan, 2018-01-23 12:45:08

How to fix the encoding error of the old DB?

There is a task to add a row to the database from input using php.
No matter how hard I butt, nothing comes out, it only writes errors:

1300 : Invalid utf8 character string: 'Ivan Ivanovich Ivanov'

mysql_query("SET NAMES 'utf8'"); 
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");

$fio = mysql_escape_string($fio);
$rank = mysql_escape_string($rank);
$razryad = mysql_escape_string($razryad);
$region = mysql_escape_string($region);
            
$query = "INSERT INTO users(name, level, rank, region) VALUES(`$fio`, `$razryad`, `$rank`, `$region`)";

$result = mysql_query($query);

MySQL is very old 5.1.41, php is also old 5.2.17
Server encoding is windows-1251, database is utf8-general-ci.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan GiBSON, 2018-01-23
@gibson_dev

I think it's enough to do
the rest is not necessary

A
A person from Kazakhstan, 2018-01-23
@LenovoId

add an AddDefaultCharset utf-8 entry to htaccess and it's time to stop using mysql and use at least mysqli or PDO

A
andrey_o_v, 2018-01-26
@andrey_o_v

1) I changed mysql_escape_string to mysql_real_escape_string because mysql_real_escape_string escapes the string according to the current encoding. read the documentation about it so that I don't copy-paste it).
2) I changed the apostrophe ` to a single quote, with an apostrophe I usually escape fields, tables, not lines, although I did not check escaped strings with an apostrophe.
3) Of course, you need to get rid of mysql and replace it with the same mysqli functions, although somewhere it can break.
4) Strange entry $fio = mysql_escape_string($fio);
it's rather register glogals is enabled, it would be more correct generic approach $fio = mysql_escape_string($_REQUEST['fio']);
but maybe the data came from $_GET or $_POST
5) And as an option, the data came in cp1251 encoding, so error 1300 : Invalid utf8 character string
$fio = mysql_real_escape_string( iconv('windows-1251', 'utf-8', $fio));

mysql_query("SET NAMES 'utf8'"); 
$fio = mysql_real_escape_string($fio);
$rank = mysql_real_escape_string($rank);
$razryad = mysql_real_escape_string($razryad);
$region = mysql_real_escape_string($region);            
$query = "INSERT INTO users(name, level, rank, region) VALUES('$fio', '$razryad', '$rank', '$region')";
$result = mysql_query($query);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question