I'm trying to make a page that displays japanese characters. These japanese characters are stored in my database. I've done my research and tried many of the suggestions given but my japanese characters still return as question marks. Currently, this is how my code looks:
<?php
$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
mb_internal_encoding('UTF-8'); ?>
<center>
<div id="fb-root"></div>
<form method="POST" id="myForm">
<h1>
<?php
$title = mysqli_query($con, "SELECT `title` FROM titles WHERE c1='a' or c2 ='b'") or die("ERROR: ". mysqli_error($con));
$title_str = mysqli_fetch_array($title);
$mystr = mb_convert_encoding($title_str[0], "UTF-8");
echo "test: ".$mystr;
?>
</h1><br/>
</form>
</body>
I've already checked if my character encoding works and it does work if I replace $title_str[0] to japanese string. Am I missing something here? I'm not sure why the encoding works on strings I manually input but not the one I got from the database.
Try using SET NAMES utf8 after connecting to MySQL:
$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}
mysqli_query($con, "SET NAMES 'UTF8'") or die("ERROR: ". mysqli_error($con));
As the manual says:
SET NAMES indicates what character set the client will use to send SQL
statements to the server... It also specifies the character set that the server should
use for sending results back to the client.
After that there is no need to use mb_convert_encoding.
Related
I have some text in a database. I use French and English. French has accents, and some special characters like ç. I use Mamp, MySQL and PHP.
I have collation latin1_swedish-ci (the default). I tried utf8_general_ci and the result is the same.
If I use in a html page, I have this in the head: <meta charset="UTF-8">
As an example, in the database I have "voilà".
When I echo the text from the database to html:
$con = mysqli_connect("localhost","root","root");
if (!$con) {
die('The connexion failed: ' . mysqli_error());
}
if (!mysqli_select_db($con, 'prova')){
echo "Connection with database was not possible";
}
$result = mysqli_query($con, "SELECT * FROM test1
WHERE id='1' ")
or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
$text = $row['first'];
echo $text; //I see: voil�
echo htmlentities($text); //I see nothing
echo utf8_encode($text); //This works: I see voilà
}
Why htmlentities does not work?
Is utf8_encode(); the way to go? I have to use that always when I output something from the database? Why do I have to use that if the collation is already UTF8? Is there any better way to store and output text with accents in a MySQL database?
After you connect to the DB you should set the client charset to UTF8:
mysqli_set_charset($con, "UTF8");
Otherwise the mysql client transforms the UTF8 'voilà' to latin1 ('cause it seems that is it's default).
Either you tell the client that I want everything in UTF8, or you get it with the default latin1, and convert it one-by-one yourself calling utf8_encose($text)
I have a problem with a mysql query. This is the code:
session_start ();
$db = mysql_connect('localhost', 'user', 'pw') or die(mysql_error());
mysql_select_db("wordpress_97") or die(mysql_error());
$names=mysql_query('set names utf8');
$tempnewpw = md5($tempnewpw);
$query = mysql_query("UPDATE wordpress_97.tUsers SET passwort = '$tempnewpw' WHERE tUsers.UserID = '$theuserid'") or die(mysql_error());
Yes I know that I shouldn't use the mysql_ functions but it's just testing..
And this is the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE wordpress_97.tUsers SET passwort = 'pwinmd5'' at line 1
I can't get away these Â...
The database shouldn't be the problem - other querys work without problems with the same structure.
Any ideas?
Thanks in advance
Delete the line and re-type it.
Most likely those are characters carried over from copy-pasting.
Regarding your second question, d41d8cd98f00b204e9800998ecf8427e is the md5 hash of null or nothing, a zero-length stream of characters.
On this line
$tempnewpw = md5($tempnewpw);
Make sure that $tempnewpw exists and has a value, I should suggest also that you use different variables instead of over-writing them.
Try this use mysql_set_charset
session_start (); # not use for the DB query's
$db = mysql_connect('localhost', 'user', 'pw') or die(mysql_error());
mysql_set_charset('utf8',$db); # add this
$db_selected = mysql_select_db("wordpress_97",$db);
//$names=mysql_query('set names utf8'); --- remove
if (!$db_selected) {
die ('Database access error : ' . mysql_error());
}
else{
$tempnewpw = md5($tempnewpw);
$query = mysql_query("UPDATE wordpress_97.tUsers SET passwort = '$tempnewpw' WHERE tUsers.UserID = '$theuserid'")
or die(mysql_error());
}
In html
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
you can try to add this line in your html head tag:
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
Don't use Word for editing. It introduces funny characters such as hex A0, which through some conversions becomes  (A-hat and a space), as seen in your text.
I hope you don't have any accented letters; I suspect they have been mangled by other things -- such as failure to be consistent in CHARACTER SET.
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?
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>
I'm specifically talking about the å, ä and ö in the swedish language. When displayed in paragraphs I use a function to substitute the letters to their HTML entities.
That works fine but now I want to have a function that let's the page admins to change the page title. I want the current title to be preloaded into the inputbox. It's not so easy to read when every ö is translated to it's html entity.
From other answers I'v checked that the files are saved as UTF-8 without BOM in Notepad++.
Database connection are written as:
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName); if ($conn->connect_error) { trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR); }
$conn->set_charset("utf-8");
In the header of the html document I have:
<meta http-equiv="content-type" content="text/html" charset="utf-8" />
Database was created as "latin1_swedish_ci" and in phpmyadmin it displays alright. The database call looks like this. The site works as it should when there is no å, ä and ö. But when there is the input box empty.
include 'db.inc.php';
$sql = "SELECT site_admin_title FROM site_admin WHERE site_admin_id = ?"; $id = 1;
$loadData = $conn->prepare($sql); if($loadData === false) { trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR); }
$loadData->bind_param('i',$id);
$loadData->execute();
$loadData->bind_result($site_admin_title);
$loadData->fetch();
$output_string = $ljusimorker_site_admin_title;
$loadData->close();
$conn->close();
echo json_encode($output_string);
Any ideas?
Have you tried using the set_charset() function this way instead (note the omission of the - character)
$conn->set_charset("utf8");
Also, you might want to change the character set of your database to UTF-8, as well.