MySQLi Tutorial MySQLi References

mysqli set_charset() Method



The mysqli::set_charset() / mysqli_set_charset() function is used to set the character set to be used when sending data from and to the database server.

Syntax

//Object-oriented style
public mysqli::set_charset(charset)

//Procedural style
mysqli_set_charset(mysql, charset)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().
charset Required. Specify the desired character set.

Return Value

Returns true on success or false on failure.

Example: Object-oriented style

The example below shows the usage of mysqli::set_charset() method.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

printf("Initial character set: %s\n", $mysqli->character_set_name());

//changing the character set to utf8mb4
$mysqli->set_charset("utf8mb4");

printf("Current character set: %s\n", $mysqli->character_set_name());

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

Initial character set: latin1
Current character set: utf8mb4

Example: Procedural style

The example below shows the usage of mysqli_set_charset() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

printf("Initial character set: %s\n", mysqli_character_set_name($mysqli));

//changing the character set to utf8mb4
mysqli_set_charset($mysqli, "utf8mb4");

printf("Current character set: %s\n", mysqli_character_set_name($mysqli));

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

Initial character set: latin1
Current character set: utf8mb4

❮ MySQLi Functions Reference