php and mysql database turkish character - php

Hello friends i know this question has in stackoverflow but i search all question answer but not solition for me. My problem is mysql and php turkish character problem.
I am using this this <meta>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
But turkish character looking this : ü�üdü
I try db connection like this:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'test');
mysql_query("SET NAMES UTF8");
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
but turkish character problem continued.
my phpmyadmin 3 tables sum collation: utf8_general_ci
message table collation: latin1_swedish_ci
<?php
$Wall = new Wall_Updates();
if(isSet($_POST['update']))
{
$update=mysql_real_escape_string($_POST['update']);
$data=$Wall->Insert_Update($id,$update);
if($data)
{
$msg_id=$data['msg_id'];
$message=tolink(htmlentities($data['message']));
$time=$data['created'];
$id=$data['uid_fk'];
$name=$data['name'];
$face=$Wall->Gravatar($id);
//$commentsarray=$Wall->Comments($msg_id);
?>
In this way screenshot link click
How can I solve the problem of Turkish character.
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});

Can you try
mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
#mysql_select_db(DB_DATABASE) or die( "Unable to select database");
mysql_set_charset('utf8');
Working ok with greek for me

HTML Entities:
Judging by your screenshot, the database contains HTML encoded entities which means that sometime before saving your data in the DB you are altering it by applying htmlentities over it.
Unfortunately if your PHP version is < 5.4 the optional parameter $encoding does not default to UTF-8 so it treats your string like ASCII.
Multi-byte vs. single-byte:
Because of this multi-byte characters are broken into single-byte characters and HTML encoded before being saved.
When retrieving the data from the database you HTML source code will have HTML entities (ex.: Ã) but your browser will render them the way you're seeing them.
Not using htmlentities should fix your problem and is recommended or you could try using html_entity_decode before outputting the data (not sure if it won't cause more trouble than it fixes).
How to check for HTML entities:
View the HTML source code of the site and check if there are any entities in the text fetched from the DB (ex.: Ã).

It is better for you to change your table's encoding to utf8 and connect to mysql like this:
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
mysql_query('set names "utf8" collate "utf8_turkish_ci" ');

Put this line below $database variable line and Try
mysql_set_charset('utf8',$database);
and while inserting this kind of data, you have to use N along with your value in your query N('$yourvalue')

Change this :
<?php
$Wall = new Wall_Updates();
if(isSet($_POST['update']))
{
$update=mysql_real_escape_string($_POST['update']);
$data=$Wall->Insert_Update($id,$update);
if($data)
{
....
?>
to this :
<?php
$Wall = new Wall_Updates();
if(isSet($_POST['update']))
{
$update=html_entity_decode(mysql_real_escape_string($_POST['update']));
$data=$Wall->Insert_Update($id,$update);
if($data)
{
....
?>

I had same problem and solved it like that
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tamirat";
$co = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
mysqli_set_charset($co, 'utf8');
Just write the connection stuff first and write 'utf8'. I hope this will help.

Related

Php mysql returning?

I have a problem, when I try to echo a cyrillic character, it return like ????
Here's code
<?
include('db.php');
$sql = "SELECT * FROM menu_items WHERE reference=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = array();
while($row = $result->fetch_object()) {
$rows[] = json_encode($row);
}
$items = implode(',',$rows);
echo '['.$items.']';
}else {
echo "ERROR";
}
?>
Any idea?
Collation : utf8_general_ci
And db.php:
<?
$servername = "localhost";
$username = "test";
$password = "Conqwe333!";
$conn=mysqli_connect($servername,$username,$password,"test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Worked after <? $conn->set_charset("utf8");?>
Add before your $sql
$conn->query('SET NAMES utf8');
You can read more about it here
Also you will need to set proper header for browser. You can do it by serveral ways for example in meta html tag or using header('Content-Type: text/html; charset=utf-8');
You should set collation per connection:
mysqli_set_charset
Also you can perform sql
SET NAMES utf8;
but it's not recommended
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
$mysqli->close();
I am assuming you are using Bulgarian and UTF8, same will work for Russian and other languages, just change "bg" to proper string.
I do not recommend you to use cp1251, because it breaks unexpectedly with apache mod_rewrite and other tools like this.
You need to do following checks:
Check if your database / table collation is some UTF8. It could be utf8_general_ci or Bulgarian - difference is minimal and is more sorting related. (utf8_general_ci is perfectly OK)
Check you have following statement executed right after connect - set names UTF8;. You can do $mysqli->query("set names utf8");
Make sure you have proper "tags". Here an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='bg' xml:lang='bg' xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Нов сайт :)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
You can include UTF8 "BOM" on the html, but it works pretty well without it. I usually work without "BOM", and when I want to be 100% complaint, I create an include file bom.php that contain just the BOM symbol and include it prior HTML template in normal PHP way, e.g. include "bom.php".
Hope this helps, if not, please comment.
EDIT:
Someone suggested you must be sure if your data is properly stored in MySQL. Easiest way is to open PHP MySQL Admin. If Cyrillic is shown there, all is OK.
I think the issue is a step back, try to first encode the cyrillic characters correctly: How to encode cyrillic in mysql?

sql data charset / charactter set , set names not working

i have the mysql connection below:
$dbLink = mysql_connect('127.0.0.1', 'root', '');
mysql_set_charset('utf8', $dbLink);
mysql_select_db('test', $dbLink);
mysql_set_charset('utf-8');
it was working fine 1 week ago, but suddenly it is not showing the utf-8 or arabic or unicode contents which are stored in the database. but now even in the database the characters has been changed like سید احمد Ø´Ûید Ú©ÛŒ صحیح and showing in the php the same. before everything was perfect. and the content was showing properly.
even now when i make a new entry in the database its showing fine but something went wrong with the old entries any help please.......
i have tried set names, mysql_set_charset & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> but nothing happened. please help otherwise my site will be hanged up......
Use MYSQLi because MYSQL is now deprecated.
To set charset utf-8 use mysqli_set_charset() like this:
$dbLink = mysqli_connect('127.0.0.1', 'root', '');
mysqli_set_charset($dbLink , 'utf8');
mysqli_select_db($dbLink, 'test');
If for any reason it is still displaying wrong characters, add this to the beginning of your documents:
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8');
// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8');
UPDATE
Select some contents from your database and output the value using iconv() and see if it shows the wright charset:
<?php
$dbLink = mysqli_connect('127.0.0.1', 'root', '');
mysqli_set_charset($dbLink , 'utf8');
mysqli_select_db($dbLink, 'test');
function get_table_contents(){
global $dbLink;
$contents = array();
$query = "SELECT * FROM ||YOUR TABLE HERE||";
$result = mysqli_query($connection, $query);
while($content = mysqli_fetch_assoc($result)){
$contents[] = $content;
}
return $contents;
}
$data = get_table_contents();
?>
<html>
<head></head>
<body>
<?php echo iconv(mb_detect_encoding($data[0]['||YOUR COLUMN||'], "UTF-8,ISO-8859-1"), "UTF-8", $data[0]['||YOUR COLUMN||']); ?>
</body>
</html>

Polish characters in mysql response

I have a problem with polish characters. I can't get correctly written words, like '?ukasz' instead of "Łukasz" or even "null", when it supposed to be "Kraków". I tried "mysql_set_charset('utf-8'/'iso-8859-1')" after mysql_connect or iconv(on json_encode($output)) and it's still the same (except now there is "Krak\u00f3" instead of "null"). I'll appreciate any help.
This is a php file for my Android app:
$id_client = $_REQUEST['id_klienta'];
$con=mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('courier_helper') or die(mysql_error());
$sql=mysql_query("SELECT * FROM `clients` WHERE id_klienta='$id_client'");
while($r=mysql_fetch_assoc($sql))
$output[]=$r;
print(json_encode($output));
mysql_close($con);
?>
You have to make sure, that you are using UTF-8 everywhere:
script file encoding (UTF-8 instead of ANSI) - you can set encoding it in Notepad++
html code (meta charset)
database table charset (when you are creating table or database)
database mysql_set_charset('utf8', $connection_obj);
database SET NAMES utf8 - run that SQL command after connecting
And one more thing - get familiar with PDO. This is my PDO connect function I use:
function DbConnect()
{
$db_host = "localhost";
$db_name = "database_name";
$db_user = "your_username";
$db_pass = "your_passwd";
$link = new PDO("mysql:host=$db_host;dbname=$db_name; charset=UTF-8", $db_user, $db_pass);
$link->exec("set names utf8;");
return $link;
}
You can use that function like this (this is PDO example):
$link = DbConnect();
$query = $link->prepare("SELECT id FROM wp_users");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
You should have your database storing data as UTF8, which means converting your existing tables.
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
You also need to make sure your connection to the database is UTF8. You can make sure of that by running a SET NAMES query right after your connect.
SET NAMES UTF8
As others mentioned, you should start using PDO.

Cyrillic symbols in INSERT query

$dblocation = "localhost";
$dbname = "xx";
$dbuser = "xx";
$dbpasswd = "xx";
$dbcnx = #mysql_connect($dblocation,$dbuser,$dbpasswd);
mysql_select_db($dbname, $dbcnx);
mysql_query("SET NAMES utf8");
mysql_query("SET COLLATION_CONNECTION=utf8_bin");
$name = mysql_real_escape_string($name);
$about = mysql_real_escape_string($about);
mysql_query("INSERT INTO votes
(name, about, active) VALUES('".$name."', '".$about."', 1 ) ")
or die(mysql_error());
It works perfectly fine when $name and $about is not cyrillic. But when it's cyrillic - script just adds a row with blank name and about fields. What do?
DB is UTF-8, manual adding rows with phpMyAdmin with cyrillic symbols works perfect, PHP-script is UTF-8, everything's UTF-8.
You should have:
1.header ("Content-Type: text/html; charset=utf-8"); or <meta http-equiv="content-type" content="text/html; charset=utf-8" />
2.mysql_query("SET NAMES 'utf8'");
3.Set your file's encoding to utf-8 without BOM
Specify character set which should be used by the connection with mysql_set_charset(...'). See http://php.net/manual/en/function.mysql-set-charset.php.
I've dealt a lot with the cyrillic and it is tricky indeed. So far in my experience I did not use any COLLATION_CONNECTION. All I do is put, as you did, all possible files in utf8. Then the fields in the DB I put in "utf8_unicode_ci" and I only use the SET NAMES params to set the connection encoding. This should be enough. Mind that the Set names might be tricky, as only a single space in extra and it will not work. I use:
define("DBENCODING", "utf8");
mysql_query("SET NAMES '".DBENCODING."'", $this->connection);
I hope I managed to help.

reading utf-8 content from mysql table [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 12 months ago.
I have a mysql table with contents
the structure is here:
I want to read and print the content of this table to html
This is my code:
<?php
include("config.php");
$global_dbh = mysql_connect($hostname, $username, $password)
or die("Could not connect to database");
mysql_select_db($db)
or die("Could not select database");
function display_db_query($query_string, $connection, $header_bool, $table_params) {
// perform the database query
$result_id = mysql_query($query_string, $connection)
or die("display_db_query:" . mysql_error());
// find out the number of columns in result
$column_count = mysql_num_fields($result_id)
or die("display_db_query:" . mysql_error());
// Here the table attributes from the $table_params variable are added
print("<TABLE $table_params >\n");
// optionally print a bold header at top of table
if($header_bool) {
print("<TR>");
for($column_num = 0; $column_num < $column_count; $column_num++) {
$field_name = mysql_field_name($result_id, $column_num);
print("<TH>$field_name</TH>");
}
print("</TR>\n");
}
// print the body of the table
while($row = mysql_fetch_row($result_id)) {
print("<TR ALIGN=LEFT VALIGN=TOP>");
for($column_num = 0; $column_num < $column_count; $column_num++) {
print("<TD>$row[$column_num]</TD>\n");
}
print("</TR>\n");
}
print("</TABLE>\n");
}
function display_db_table($tablename, $connection, $header_bool, $table_params) {
$query_string = "SELECT * FROM $tablename";
display_db_query($query_string, $connection,
$header_bool, $table_params);
}
?>
<HTML><HEAD><TITLE>Displaying a MySQL table</TITLE></HEAD>
<BODY>
<TABLE><TR><TD>
<?php
//In this example the table name to be displayed is static, but it could be taken from a form
$table = "submits";
display_db_table($table, $global_dbh,
TRUE, "border='2'");
?>
</TD></TR></TABLE></BODY></HTML>
but I get ???????? as the results:
Where is my mistake?
Four good steps to always get correctly encoded UTF-8 text:
1) Run this query before any other query:
mysql_query("set names 'utf8'");
2) Add this to your HTML head:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
3) Add this at top of your PHP code:
header("Content-Type: text/html;charset=UTF-8");
4) Save your file with UTF-8 without BOM encoding using Notepad++ or any other good text-editor / IDE.
Set the charset as utf8 as follows:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
You are not defining your HTML page as UTF-8. See this question on ways to do that.
You may also need to set your database connection explicitly to UTF8. Doing a
mysql_query("SET NAMES utf8;");
^
Put it right under your database connection script or include and MAKE sure you have it placed before you do any necessary queries. Also, for collocation please take the time to make sure your
setting it for your proper syntax type and general_ci seems working good for me when used. As a finale, clear your cache after banging your head, set your browser to proper encoding toolbar->view->encoding
Setting the connection to UTF8 after establishing the connection takes care of the problem. Don't do this if the first step already works.
UTF-8 content from MySQL table with PDO
To correctly get latin characters and so on from a MySQL table with PDO,
there is an hidden info coming from a "User Contributed Note" in the PHP manual website
(the crazy thing is that originally, that contribution was downvoted, now luckily turned to positive .. sometime some people need to got blamed)
my credits credits go to this article that pulled the solution and probably made that "User Contributed Note" to turn positive
If you want to have a clean database connection with correct Unicode characters
$this->dbh = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8",
DB_USER,
DB_PASS);
try this :
mysql_set_charset('utf8', $yourConnection);
Old ways have been deprecated. If you are using PHP > 5.0.5 and using mysqli the new syntax is now:
$connection->set_charset("utf8")
Where $connection is a reference to your connection to the DB.
I tried several solutions but the only one that worked
is that of Hari Dass:
$conn->set_charset("utf8");

Categories