gosulove gosulove - 1 month ago 5x
MySQL Question

how to convert mysqli_set_charset($conn,"utf8") into PDO format in MYSQL?

I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
} else {
echo "0 results";

I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.

However, when I try to do it in PDO , it shows 1 error when I insert data.

public function __construct(){
try {

$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here

catch(PDOException $e)
echo "Connection failed: " . $e->getMessage();

I got this error

Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...

My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?


You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.

In PDO the charset usually is being specified within the connection string, like this:

$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");