How to display Germany Umlauts (ü, ä, ö) from sql in Php? - php

I am trying to display this German character the proper way, if I don't use htmlentities() the output is unabh�ngig, but when I try to use htmlentities() the word is missing, why is that?
<?php
$str = htmlentities("unabhängig");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset='utf-8'>
</head>
<body>
</body>
<div><?php echo $str;?></div>

I had the same problem with the ü, ä, etc.
Right after selecting the database I implemented this two lines:
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");
as suggested here:
http://www.flashhilfe.de/forum/serverseitige-programmierung/php-mysql-wie-utf-8-beim-connect-festlegen-225225-225225.html
Best, Yannis

You should just be able to send ü without encoding it separately by ensuring that the charset is set to utf-8 using HTTP header.
If for some reason you can't do that, use:
Ü = Ü
or
ü = ü

This is the format for charset:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Make sure your encoding is not being forced by htaccess or apache. check what is the selected encoding in your browser when you view the site, if it is not utf-8, then it is being forced. If forced you can add this to htaccess
AddDefaultCharset UTF-8
Make sure your database table is in utf-8
Make sure your connection to your database is in utf-8 http://php.net/manual/en/function.mysql-set-charset.php
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);
You can pass UTF-8 encoding to htmlentities to make it use correct encoding. or you can use htmlspecialchars http://php.net/manual/en/function.htmlentities.php

And if you don't want to worry about so many different charset codings or if htmlentities doesn't work for you, here the alternative:
I used mysqli DB connection (and PHPV5) Form post for writing/inserting to MySQl DB.
$Notes = $_POST['Notes']; //can be text input or textarea.
$Notes = str_replace('"', '"', $Notes); //double quotes for mailto: emails.
$von = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é"); //to correct double whitepaces as well
$zu = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é");
$Notes = str_replace($von, $zu, $Notes);
echo " Notes:".$Notes."<br>" ;
$Notes = mysqli_real_escape_string($link, $Notes); //for recommended mysqli DB connection.
//$Notes = mysql_real_escape_string($Notes); //for old deprecated mysql DB connection.
// mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement
echo " Notes:".$Notes ; //ready for inserting
enter code here
//Optional:
$charset = mysqli_character_set_name($link); //only works for mysqli DB connection
printf ("To check your character set but not necessary %s\n",$charset);

Related

encode & decode html code from mssql in php

I just added a WYSIWYG editor on my website so my users can format their content any way they want. The editor works fine and is successfully saving the html coded content on the database.
The problem is when I try to view the content from MSSQL database, here's what it shows on the webpage:
�fa)2016-03-16 12:35:19.000Pg;e)#��+�!!P�P+�fa ��`��,�!H+�H+� �����,�1 � �||�`���X���sql�1 m!���1rsode!!htmlspecialchars_decode!flyerflyer9
���9����X� ������x�����`��1�r~����X�����id!1+!connection.phpflyer_id,� x����,�hpr_id,� x����,�) ����a)���]�� �|����*?���#B�r~�������������Ya�v�&������C:\inetpub\wwwroot\123\test_en_de.phpY43ectsql�9SELECT * FROM flyer_master Where flyer_id = '9����#����)`!�##��,��,��,��)' ��Errorresultodbc_exec� h����,�
The php code to display the content is:
<?php
include("connection.php");
$flyer_id = 43 ;
$sql = ("SELECT * FROM flyer_master Where flyer_id = '".$flyer_id."' ") or die ("Error");
$result=odbc_exec($connect,$sql)or die(exit("Error en odbc_exec"));
while(odbc_fetch_row($result))
{
$id = odbc_result($result,1);
$name = odbc_result($result,2);
$flyer = odbc_result($result,3);
}
echo $flyer;
//$a = htmlentities($flyer);
echo "<br>";
echo htmlspecialchars_decode(flyer);
//echo $de_code = html_entity_decode($flyer);
//echo $de_code = htmlspecialchars($flyer ,ENT_QUOTES, 'UTF-8');
?>
Can you please help me correct this code so the html coded text is displayed properly? Or, is there another way to do this?
Note i m using php+odbc+Microsoft SQL Server 2008 R2 (RTM).
You can use the utf-8 encoding
I needed to access the database from within one particular webhosting service. Pages are UTF-8 encoded and data received by forms should be inserted into database without changing the encoding. The database is also in UTF-8.
Neither SET character set 'utf8' or SET names 'utf8' worked properly here, so this workaround made sure all variables are set to utf-8.
<?php
// ... (creating a connection to mysql) ...
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);
$re = mysql_query('SHOW VARIABLES LIKE "%character_set%";')or die(mysql_error());
while ($r = mysql_fetch_assoc($re)) {var_dump ($r); echo "<br />";} exit;
?>`
All important variables are now utf-8 and we can safely use INSERTs or SELECTs with mysql_escape_string($var) without any encoding functions.

Can't add an UTF-8 string into MySQL? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 7 years ago.
I can't add an UTF-8 string into MySQL DB. Here's the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
$temp='papà';
mysql_query("SET NAMES utf8");
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
mysql_query("INSERT INTO comment VALUE ('$temp')") or die(mysql_error());
?>
</body>
</html>
the variable in DB is a CHAR(120) and with a non-utf8 string it works properly.
The error is the generic "You have an error in your SQL Syntax ecc."
Thanks in advance for your help.
Use the following code:
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
$temp='papà';
mysqli_query("INSERT INTO comment VALUE ('$temp')") or die(mysqli_error());
?>
</body>
</html>
stop using mysql_* and start using mysqli_* or use PDO
After converting to mysqli_*, use set_charset. Don't do the rest of the SETs. (PDO has the charset in the dsn.)
Is the column in the table CHARACTER SET utf8?
Are the bytes in the encoded utf8-encoded? In utf8, then hex for à is C3A0. In latin1, it is F0.
It is almost always better to use VARCHAR than CHAR.
If you have more troubles, do SELECT col, HEX(col) FROMcoment...; -- that will probably give the best clue of what still broken.

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.

Problems in inserting utf-8 string into database and then outputting it to web page

I am learning PHP programming, so I have setup testing database and try to do various things with it. So situation is like that:
Database collation is utf8_general_ci.
There is table "books" created by query
create table books
( isbn char(13) not null primary key,
author char(50),
title char(100),
price float(4,2)
);
Then it is filled with some sample data - note that text entries are in russian. This query is saved as utf-8 without BOM .sql and executed.
insert into books values
("5-8459-0046-8", "Майкл Морган", "Java 2. Руководство разработчика", 34.99),
("5-8459-1082-X", "Кристофер Негус", "Linux. Библия пользователя", 24.99),
("5-8459-1134-6", "Марина Смолина", "CorelDRAW X3. Самоучитель", 24.99),
("5-8459-0426-9", "Родерик Смит", "Сетевые средства Linux", 49.99);
When I review contents of created table via phpMyAdmin, I get correct results.
When I retrieve data from this table and try to display it via php, I get question marks instead of russian symbols. Here is piece of my php code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Books</title>
</head>
<body>
<?php
header("Content-type: text/html; charset=utf-8");
mysqli_set_charset('utf8');
# $db = new mysqli('localhost', 'login', 'password', 'database');
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars (stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
...
And here is the output:
1. Название: Java 2. ??????????? ????????????
Автор: ????? ??????
ISBN: 5-8459-0046-8
Цена: 34.99
Can someone point out what I am doing wrong?
Can someone point out what I am doing wrong?
Yes, I can.
You didn't tell Mysql server, what data encoding you want.
Mysql can supply any encoding in case your page encoding is different from stored data encoding. And recode it on the fly.
Thus, it needs to be told of client's preferred encoding (your PHP code being that database client).
By default it's latin1. Thus, because there is no such symbols in the latin1 character table, question marks being returned instead.
There are 2 ways to tell mysql what encoding we want:
a slightly more preferred one is mysqli_set_charset() function (method in your case).
less preferred one is SET NAMES query.
But as long as you are using mysqli extension properly, doesn't really matter. (though you aren't)
Note that in mysql this encoding is called utf8, without dashes or spaces.
Try to set output charset:
SET NAMES 'utf-8'
SET CHARACTER SET utf-8
Create .htaccess file:
AddDefaultCharset utf-8
AddCharset utf-8 *
CharsetSourceEnc utf-8
CharsetDefault utf-8
Save files in UTF-8 without BOM.
Set charset in html head.
After your mysql_connect, set your connection to UTF-8 :
mysql_query("SET NAMES utf8");
Follow Alexander advices for .htaccess, header and files encoding
You probably need to call mysqli_set_charset('utf8'); after you set up your connection with new mysqli(...) as it works on a link rather than a global setting.
so..
# $db = new mysqli('localhost', 'login', 'password', 'database');
mysqli_set_charset($db, 'utf8');
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
By the way, that query seems to be open to SQL-injection unless $searchterm is sanitized. Just something to keep in mind, consider using prepared statements.
And using # to suppress errors is generally not recommended, especially not during development. Better to deal with error-conditions.
after your mysql_query add
#mysql_query("SET character_set_server='utf8'; ");
#mysql_query("SET character_set_client='utf8'; ");
#mysql_query("SET character_set_results='utf8'; ");
#mysql_query("SET character_set_connection='utf8'; ");
#mysql_query("SET character_set_database='utf8'; ");
#mysql_query("SET collation_connection='utf8_general_ci'; ");
#mysql_query("SET collation_database='utf8_general_ci'; ");
#mysql_query("SET collation_server='utf8_general_ci'; ");
Try to put also in the HTML document Head the meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
this is different to the HTTP header header("Content-type: text/html; charset=utf-8");

Insert a ♥ into MySQL (heart character) via PHP

I'm having a heck of a time getting ♥ type characters into my database using php.
I've got UTF-8 setting on the page
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
and
<?php
$line = $_REQUEST['line'];
$line = stripslashes($line);
$line = htmlspecialchars($line);
$line = trim($line);
$line = mysql_real_escape_string($line);
mysql_query("SET CHARACTER SET utf8");
$sql = "INSERT INTO posts (txt) values ('$line')";
mysql_query($sql, $cn);
?>
the result of the insert is a ? character
i'm sure there are people who've done this, but I'm really having trouble getting it right.
edit:
the MySQL table's collation and field's encoding is also set to utf8_unicode_ci
I believe you have to do: SET NAMES utf8 as your first query.

Categories