sql data charset / charactter set , set names not working - php

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>

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?

php and mysql database turkish character

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.

Encoding to Hebrew - PHP, mysqli

I'm using MySQLi to retrieve information from the database. All of my pages are encoded with UTF-8 without BOM, i have 2 pages to deal with, but the main problem is that on the database the information is showed in a regular way - but when i retrieve it it goes like this:
����� ����� - ���?
on the phpMyAdmin panel - the columns are latin1_general_ci (i tried to make it utf8_general as well - same output!).
the "mysql.php":
<?php
header('Content-type: text/xhtml; charset=windows-1255');
$mysql = new mysqli('localhost', 'elenbyin_vadim', 'pass33323', 'elenbyin_vadim');
?>
the "index.php", main parts:
<?php
include ('mysql.php');
include('functions.php');
if($_GET["lang"] == 'rus')
$lang = 'rus';
else if($_GET["lang"] == 'heb')
$lang = 'heb';
else
$lang = 'heb';
......
<div class="main_text">
<?
$result = $mysql->query('SELECT * FROM homepage');
while($row = mysqli_fetch_array($result)){
echo "".$row['title']."<br />".$row['text_heb']."";
}
?>
</div>
can someone help my to solve this problem?
You'll have to change the charset for it to work:
<?php
$mysql->set_charset('utf8');
$result = $mysql->query('SELECT * FROM homepage');
...
?>
#Class's comment - If you need it in all your pages you can add it to mysql.php:
<?php
header('Content-type: text/xhtml; charset=windows-1255');
$mysql = new mysqli('localhost', 'elenbyin_vadim', 'pass33323', 'elenbyin_vadim');
$mysql->set_charset('utf8');
?>
Also, make sure you set your collation to utf8_general_ci.
An older method will be to set the names to utf8:
<?php
$mysql->query("SET NAMES 'utf8'");
$result = $mysql->query('SELECT * FROM homepage');
...
?>
However according to set_charset() docs the first is preferrable:
Note: This is the preferred way to change the charset. Using
mysqli_query() to set it (such as SET NAMES utf8) is not recommended.
See the MySQL character set concepts section for more information.

php echo page title in foreign characters

I want to echo page title from database value.
<title><?php echo $data['art_title'] ?></title>
But that language is Chinese. Title is not showing correctly. It's look like this now.
how to fix this problem? thank you.
When you saving your page choose its endoding utf-8 or another chinese supported encoding.
If you already are doing things right (writing both string in UTF-8) the problem can be Chrome/Firefox tryiing to use a font that is not unicode aware for the titles (?)... if thats the case, theres nothing you can do (report it?)
Just in case, make sure your page is correctly encoded (text in utf8, with the page declared in utf8).
UPDATE:
You could be hitting a OS/Browser bug:
http://code.google.com/p/chromium/issues/detail?id=90752
I found a solution.
$sql = 'SET CHARACTER SET utf8';
here is full code
<?php
// MySQl connection
$db = mysql_connect('host', 'user', 'password');
// Select the database
mysql_select_db('db',$db);
$sql = 'SET CHARACTER SET utf8';
$result = mysql_query($sql, $db);
// SQL query
$sql = "SELECT art_title, art_meta FROM article WHERE art_id=".$_GET['art_id'];
// Send the query
$req = mysql_query($sql) or die('Error SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
?>
<meta name="keywords" content="<?php echo $data['art_meta']; ?>" />
<title><?php echo $data['art_title']; ?></title>

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