PHP mysqli_set_charset() Function
Definition and Usage
The mysqli_set_charset() function is used to specify the default character set to send data to the database server from mysqli client.
Syntax
mysqli_set_charset($con, charset)
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
con(Mandatory) This is an object representing a connection to MySQL Server. |
| 2 |
charset(Mandatory) Name of the character set which you need to set as default. |
Return Values
The mysqli_set_charset() function returns true if incase of success and false if failed.
PHP Version
This function was first introduced in PHP Version 5 and works works in all the later versions.
Example
Following example demonstrates the usage of the mysqli_set_charset() function (in procedural style) −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Name of the character set
$res = mysqli_set_charset($con, "utf8");
print_r($res);
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
1
Example
In object oriented style the syntax of this function is $con->set_charset(); Following is the example of this function in object oriented style $minus;
<?php
$con = new mysqli("localhost", "root", "password", "test");
//Name of the character set
$res = $con->set_charset("utf8");
print($res);
//Closing the connection
$con -> close();
?>
This will produce following result −
1
Example
<?php
$connection_mysql = mysqli_connect("localhost","root","password","mydb");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connection_mysql,"utf8");
echo mysqli_character_set_name($connection_mysql);
mysqli_close($connection_mysql);
?>
This will produce following result −
utf8