MySQL UTF8 Connection Using PHP
Are you finding a way to get your utf8 characters displayed in your website content?
Actually, there are many languages that use uft8 characters while some others use the alphabet/Latin characters. This PHP function will help you to query your utf8 database contents to your website.
However, there are two functions you can see here: standard query named exec_query() and utf8 query named exec_query_utf8().
INSTRUCTION
You may create a external php file that will be included to all your working files. Now, let's name the file as
connect_db.php
So, now we will put the bellow code to the above file.
$dbhost = "localhost";
$dbuser = "yourUsername";
$dbpass = "yourDatabasePassword";
$dbname = "yourDatabaseName";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($conn));
function exec_query($query){
global $conn;
$result = mysqli_query($conn, $query) or
die("could not execute query $query");
return $result;
}
function exec_query_utf8($query){
exec_query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
$result = exec_query($query);
return $result;
}
Before the function can be used, we may need to configure the
mysqli_connect first. Now suppose that we're working in the
localhost with database username
yourUsername, database password
yourDatabasePassword, and database name
yourDatabaseName.
With the above configuration, the functions now can be used in your working project.
Here is how to use the utf8 query function:
$qry = exec_query_utf8("SELECT * FROM tblname WHERE fieldName='value'");
while($row = mysqli_fetch_assoc($qry)){
echo $row['fieldName'];
}
The above code will query the utf8 characters from your database to your website content or to where you need.