Dutch PHP Conference 2025 - Call For Papers

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charsetSets the client character set

Увага

Це розширення застаріле, починаючи з PHP 5.5.0, та вилучене з PHP 7.0.0. Натомість використовуються розширення MySQLi або PDO_MySQL. Докладніше описано у керівництві MySQL: вибір API. Цю функцію можна замінити на:

Опис

mysql_set_charset(string $charset, resource $link_identifier = NULL): bool

Sets the default character set for the current connection.

Параметри

charset

A valid character set name.

link_identifier

З'єднання MySQL. Якщо не задано, буде обрано останнє з'єднання, встановлене функцією mysql_connect(). Якщо з'єднатися не вдалось, функція спробує встановити нове, ніби викликавши функцію mysql_connect() без параметрів. Якщо з'єднання не вдалося знайти або встановити, буде виведено повідомлення рівня E_WARNING

Значення, що повертаються

Повертає true у разі успіху або false в разі помилки.

Примітки

Зауваження:

This function requires MySQL 5.0.7 or later.

Зауваження:

This is the preferred way to change the charset. Using mysql_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.

Прогляньте також

add a note

User Contributed Notes 3 notes

up
33
Ashus
15 years ago
I needed to access the database from within one particular webhosting service. Pages are UTF-8 encoded and data received by forms should be inserted into database without changing the encoding. The database is also in UTF-8.

Neither SET character set 'utf8' or SET names 'utf8' worked properly here, so this workaround made sure all variables are set to utf-8.

<?php

// ... (creating a connection to mysql) ...

mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

$re = mysql_query('SHOW VARIABLES LIKE "%character_set%";')or die(mysql_error());
while (
$r = mysql_fetch_assoc($re)) {var_dump ($r); echo "<br />";} exit;

?>

All important variables are now utf-8 and we can safely use INSERTs or SELECTs with mysql_escape_string($var) without any encoding functions.
up
15
nabeelmoidu at gmail dot com
16 years ago
Here's an example of how to use this feature :

I'm using PHP 5.2.5 from http://oss.oracle.com/projects/php/

I wanted to store arabic characters as UTF8 in the database and as suggested in many of the google results, I tried using

mysql_query("SET NAMES 'utf8'");

and

mysql_query("SET CHARACTER SET utf8 ");

but it did not work.

Using the following, it worked flawlessly

$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);

Once this is set we need not manually encode the text into utf using utf8_encode() or other functions. The arabic ( or any UTF8 supported ) text can be passed directly to the database and it is automatically converted by PHP.
For eg.
<?php
$link
= mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);
$db_selected = mysql_select_db('emp_feedback', $link);
if (!
$db_selected) { die ('Database access error : ' . mysql_error());}
$query = "INSERT INTO feedback ( EmpName, Message ) VALUES ('$_empName','$_message')";
mysql_query($query) or die('Error, Feedback insert into database failed');
?>
Note that here $_empName is stored in English while $_message is in Arabic.
up
1
Janez R.
17 years ago
I assume that this is an equivalent in previous versions of php (add some parameter validation and default values though!):
<?
if (!function_exists('mysql_set_charset')) {
function mysql_set_charset($charset,$dbh)
{
return mysql_query("set names $charset",$dbh);
}
}
?>
To Top