wpdb::set_charset() WordPress Method

The wpdb::set_charset() method is used to set the character set for a database connection. This is useful if you need to ensure that all data is stored and retrieved in a consistent character set. The method takes two parameters: the database connection to use (which can be either a WordPress database object or a resource link identifier), and the character set to use (which must be a valid character set for the database).

wpdb::set_charset( mysqli|resource $dbh, string $charset = null, string $collate = null ) #

Sets the connection’s character set.


Parameters

$dbh

(mysqli|resource)(Required)The connection returned by mysqli_connect() or mysql_connect().

$charset

(string)(Optional) The character set.

Default value: null

$collate

(string)(Optional) The collation.

Default value: null


Top ↑

Source

File: wp-includes/wp-db.php

	public function set_charset( $dbh, $charset = null, $collate = null ) {
		if ( ! isset( $charset ) ) {
			$charset = $this->charset;
		}
		if ( ! isset( $collate ) ) {
			$collate = $this->collate;
		}
		if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
			$set_charset_succeeded = true;

			if ( $this->use_mysqli ) {
				if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
					$set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
				}

				if ( $set_charset_succeeded ) {
					$query = $this->prepare( 'SET NAMES %s', $charset );
					if ( ! empty( $collate ) ) {
						$query .= $this->prepare( ' COLLATE %s', $collate );
					}
					mysqli_query( $dbh, $query );
				}
			} else {
				if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
					$set_charset_succeeded = mysql_set_charset( $charset, $dbh );
				}
				if ( $set_charset_succeeded ) {
					$query = $this->prepare( 'SET NAMES %s', $charset );
					if ( ! empty( $collate ) ) {
						$query .= $this->prepare( ' COLLATE %s', $collate );
					}
					mysql_query( $query, $dbh );
				}
			}
		}
	}


Top ↑

Changelog

Changelog
VersionDescription
3.1.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.