PHP / Mysql special character inserts being trunca

2020-02-29 06:16发布

问题:

I am having an issue with inserting words with special characters into my database. The word seems to get truncated at the special character.

I am using MySQL 5.1.41 the collation on my database is utf8_general_ci. I am using PDO to facilitate database interaction.

Here is an example of what I am doing.

//$db is a PDO object
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
//word with a special character 
$word = "pépite";
$sql = "INSERT INTO keyword(key_name) VALUES(?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($word));

When this executes I just get "p" in my database, it seems the character é and everything after it is truncated. I'm not sure what I am doing wrong here. If anyone could suggest what I am doing incorrectly it would be very much appreciated. Thanks!

回答1:

Try this

$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
$word = utf8_encode('pépite');
$sql = "INSERT INTO keyword(key_name) VALUES(?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($word));

utf8_encode | utf8_decode