Skip to content

Instantly share code, notes, and snippets.

@nasirkhan
Last active August 8, 2018 09:06
Show Gist options
  • Save nasirkhan/a0f94c30b9fe439d7187a336e244f30f to your computer and use it in GitHub Desktop.
Save nasirkhan/a0f94c30b9fe439d7187a336e244f30f to your computer and use it in GitHub Desktop.
MySQL PDO Unicode Issue fix
<?php
/*
* The following function will create a PDO connection form PHP.
* It sovles the issue of inserting the Unicode Characters.
*/
function connect_db() {
$servername = "localhost";
$db_username = "root";
$db_password = "root";
$db_name = "DATABASE_NAME";
try {
$conn = new PDO("mysql:host=$servername;dbname=$db_name;charset=utf8", $db_username, $db_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAME'utf8'");
echo "\nPDO connection object created\n";
return $conn;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment