Json编码 - 无效的utf-8序列

Everything I've been doing that anyhow relates to the databases throw me the json_encode(): invalid utf-8 sequence warning.

Earlier it was because of the doctrine usage, I couldn't deal with it so I began doing something else in my project...but now I need to use the PDO connection in one place, and the problem has returned.

The warning appears even with some random database configs (but where host = 'localhost').


The code:

$dsn = 'mysql:dbname='.$form['dbname']->getData().';host='.$form['host']->getData();
$pdo = new \PDO($dsn, $form['username']->getData(), $form['password']->getData());

Input example:

dbname = 'fdsfdsf'
username = 'fdsfdsf'
password = 'fsdfds'
host = 'localhost'

The exact error:

ContextErrorException: Warning: json_encode(): Invalid UTF-8 sequence in argument in C:\xampp\htdocs\cc\app\cache\dev\classes.php line 4520

What have I tried already?

  1. mysql_set_charset()
  2. Escaping input strings
  3. @ syntax
  4. Setting utf8 encoding for the controller file
  5. Setting utf8-general encoding for mysql tables/database

    $dsn = 'mysql:dbname='.htmlentities($form['dbname']->getData(), ENT_QUOTES, 'utf-8', FALSE).';host='.htmlentities($form['host']->getData(), ENT_QUOTES, 'utf-8', FALSE);
    $pdo = @new \PDO($dsn, htmlentities($form['username']->getData(), ENT_QUOTES, 'utf-8', FALSE), htmlentities($form['password']->getData(), ENT_QUOTES, 'utf-8', FALSE));
    mysql_set_charset('utf-8');
    

What's wrong?

usually mysql_set_charset get 'utf8' and not 'utf-8' so maybe this is the problem.