Special Characters do not get displayed properly - php

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.

Related

Problems with swedish letters MySQL and LAMP

I have struggled with this some time. I could not get it to work.
On the url http://course.easec.se/problem.pdf I have put together what I have done so far!
Any suggestions?
<?php
header('Content-Type: text/html; charset=ISO-8859-1'); //no changes
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "db_test4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset("utf8");
echo "From PHP Script ååååå\n"; //to see if there is problem when edit the script
$sql = "SELECT * FROM test_tbl";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Kundid: " . $row["kund_id"]. " - Förnamn: " . $row["fnamn"]. " - Efternamn: " . $row["enamn"]. " - Adress:" . $row["adress1"] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Client:
It works now, seems do be my editor, when I tried ANSI instead of UTF-8 and Changes the header to !
enter image description here
Directly below
$conn = new mysqli($servername, $username, $password, $dbname);
add
$conn->set_charset("utf8");
Note: In addition you should also make sure that the charset of your HTML (in the <head> tag) is set to utf-8, like <meta charset="utf-8">
Use:
header('Content-Type: text/html; charset=ISO-8859-1');
Instead of:
header('Content-type: text/html; charset=utf-8');
No need to use inside while loop, use top of the page before print anything.
I like how you set your question in a PDF, somewhat original :-D . Now, the answer to your problem will be found here. Read the whole question and as many of the answers as you can.
then as a last effort I change editor to ANSI instead of UTF-8 then it works!
Due to this the issue is your internal PHP script encoding so Reaseach using PHP Multibyte String and setting your PHP code to :
<?php
mb_internal_encoding('UTF-8'); //this is the important one!
mb_http_output('UTF-8');
mb_http_input('UTF-8');
to ensure your PHP code is also UTF-8 complient when executed. You can also (or should be able to) edit the settings in your IDE editor to save PHP files without UTF-8 BOM (Byte Order Mark) which will also solve this problem and save them as UTF-8 understandable by other services.
Additional Notes (cos I like to moan about MySQL UTF-8):
MySQL UTF-8 is NOT the full UTF-8 . Solutions are offered in the linked thread above, some general additions:
1) You want to always use UTF8mb4 (and ideally _unicode_ci).
2) In the final screenshot of your PDF you should to set as many of these as practical to utf8mb4_unicode_ci.
3) Setting the connection character set is vital, even if the server and the client both use utf8mb4 if the connection is only utf-8 it brings everything else down to that low point.
4) Recommended:
header('Content-Type: text/html; charset=UTF-8'); //UTF-8
Only MySQL UTF-8 is broken, other implementatios of it is not and is perfectly usable as and is generally regarded as an HTML standard.

Store and output text with accents

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)

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 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