Jump to content

Insert foreign characters using PDO


Recommended Posts

Hello, I want to be able to insert foreign characters into my database. However, my problem is that it is inserting the characters as question marks instead. I am using PDO as my API library. Let's say I want to insert a Japanese character like so

ハッカー

I get the following

????

I know it has something to do with setting the character set using UTF-8, however, I've tried that with the following codes below and nothing has changed.

 

Here is my Database connection.

$user = 'root';
$pass = 'root';

$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', $user, $pass, $options);

Here is my datbase insert.

$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

$prepare = $db->prepare("INSERT INTO post (message) VALUES (:message);");
$parameters = array(':message' => $message);
$prepare->execute($parameters);
Link to comment
https://forums.phpfreaks.com/topic/296681-insert-foreign-characters-using-pdo/
Share on other sites

 

Hello, I want to be able to insert foreign characters into my database. However, my problem is that it is inserting the characters as question marks instead. I am using PDO as my API library. Let's say I want to insert a Japanese character like so

ハッカー

I get the following

????

I know it has something to do with setting the character set using UTF-8, however, I've tried that with the following codes below and nothing has changed.

 

Here is my Database connection.

$user = 'root';
$pass = 'root';

$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', $user, $pass, $options);

Here is my datbase insert.

$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

$prepare = $db->prepare("INSERT INTO post (message) VALUES (:message);");
$parameters = array(':message' => $message);
$prepare->execute($parameters);

Try changing

 

$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

 

to

 

$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);

Try changing

 

$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

 

to

 

$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);

Thanks, but I think I solved this with the approach I was looking for.

 

Had to delete the ;charset=utf8 part and then I had to add this line below it.

$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.