English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP mysqli_set_charset() Function Usage and Example

PHP MySQLi Reference Manual

mysqli_set_charset() function sets the default character encoding

Definition and Usage

mysqli_set_charset()This function is used to specify the default character set, the default character set for sending data from the mysqli client to the database server.

Note: When using this function on the Windows platform, you need the MySQL client library 4.1.11 or above version (MySQL 5.0 is required 5.0.6 or above version).

Syntax

mysqli_set_charset($con, charset)

Parameter

NumberParameters and descriptions
1

con (required)

This is an object representing the connection to the MySQL Server.

2

charset (required)

The name of the character set to be set as the default.

Return value

mysqli_set_charset()Returns TRUE on success, or FALSE on failure.

PHP version

This function was originally introduced in PHP version5introduced and can be used in all higher versions.

Online example

The following examples demonstratemysqli_set_charset()Usage of the function (procedural style)-

<?php
   //Establish connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");
   //Character set name
   $res = mysqli_set_charset($con, "utf8");
   print_r($res);
   //Close connection
   mysqli_close($con);
?>

Output result

1

Online example

In object-oriented style, the syntax of this function is$con-> set_charset();.Here is an example of this function in object-oriented style;

<?php
   $con = new mysqli("localhost", "root", "password", "test");
   //Character set name
   $res = $con-> set_charset("utf8");
   print($res);
   //Close connection
   $con -> close();
?>

Output result

1

Online example

Set default client character set:

<?php
   $connection_mysql = mysqli_connect("localhost","root","password","mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Connection to MySQL failed: " . mysqli_connect_error();
   }
   
   mysqli_set_charset($connection_mysql,"utf8");
   
   echo mysqli_character_set_name($connection_mysql);
   
   mysqli_close($connection_mysql);  
?>

Output result

utf8

PHP MySQLi Reference Manual