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.
Related
How can i get arabic data from MSSQL database using ODBC connection?
It appears as ????.
I tried below listed solutions which are not working for me.
1) 'Name'=>iconv("unicode", "utf-8", $row["Name"]),
2) 'Name'=>iconv("Arabic_CI_AS", "utf-8", $row["Name"]),
3) mysql_query("SET NAMES utf8");
4) mysql_query('SET CHARACTER SET utf8');
5) <meta charset="UTF-8" />
6) 'Name'=>mb_convert_encoding($row["Name"], 'UTF-8', 'SJIS'),
Code snippet:
$customer_query="select serial,CR_ID,Name,Email,Customer_NameE from [CRM].[005_Customers_tbl]";
$query = odbc_exec($link,$customer_query);
$total_count=odbc_num_rows($query);
$json = array();
if($total_count>0){
while ($row = odbc_fetch_array($query)) {
$json[] = array('serial'=>$row['serial'],
'CR_ID'=>$row['CR_ID'],
'Name'=>$row["Name"],
'Email'=>$row['Email'],
'Customer_NameE'=>$row['Customer_NameE']);
}
}
$result['customer']=$json;
I know that it's achievable using change collation of table but it's not possible for this application due to some limitations.
Any other possibilities to achieve that ?
First you have to put below line
<meta charset="UCS-2"/>
and do casting in query like this
$var = "select CAST(Name as VARBINARY(150) as Name) form $table_name;
and then use this line for convert ??? text to arabic language.
$name = iconv('UCS-2LE','UTF-8',$name)
I found a lot of answers for my problem but nothing worked.
I have Chinese characters in my MYSQL database and when I SELECT my field in php I get '???' instead of '我们的产品'. I was able to INSERT this characters from php to my MYSQL database.
With characters like 'éà' I have no problem to get them in PHP.
My database, table and field are encoded in utf8_unicode_ci. There is my php file(also encoded in utf-8) :
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<?php
$query = mysql_query("SELECT * FROM table");
$arr = mysql_fetch_array($query))
echo ($arr['field']);
?>
If I replace my code like this it prints 我们的产品 :
$query = mysql_query("SELECT '我们的产品'");
arr = mysql_fetch_array($query)
echo ($arr[0]);
I hope I gave enough information.
set charset as utf8 before making a mysql query, like this
mysql_connect('localhost','mysql_user','your_password');
mysql_select_db('my_db') or die( "Unable to select database");
mysql_set_charset('UTF8');
mysql_query('Your query here');
I'm trying to insert data in a mysql database. These data often has german umlaute in it.
I'm using this method:
function insertMenue($content, $date) {
$session = $_SESSION['aid'];
global $pdo;
$pdo->exec('SET CHARACTER SET utf8');
$params = ["menue", "<p>".changeAttr($content)."</p>", $date, $session];
// Check all your params are set...
// Although you may want to consider checking these before entering this block
print_r($params);
echo "c".changeAttr($content);
print_r("v". changeAttr($content));
$sql = "INSERT INTO menue( type
, content
, date
, creator
)
VALUES( ?
, ?
, ?
, ?
)";
try {
$sth = $pdo->prepare($sql);
$sth->execute($params);
} catch (PDOException $e) {
throw new pdoDbException($e);
}
}
As you see I'm already doing some debugging.
I'm getting the data from an Excel .xls file.
The print_r grants an output like this:
Salat
****
Trutenpiccata Tomatensauce
Spaghetti
Gem�sebuffet
-
****
Saisonfr�chte
When I check the mysql database everything including the � and after gets deleted.
Like:
Salat
****
Trutenpiccata Tomatensauce
Spaghetti
Gem
I tried to encode the data as utf-8 from the insert method on and I set the database to utf-8 by:
ALTER DATABASE mensaapp CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE menue CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
Where do I miss the point to encode the data to utf-8?
You need to put the charset in your html code too.
This is what helped me with my umlaute ;)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" /><!-- THIS IS WHAT NEEDED -->
</head>
<body>
</body>
</html>
After adding it, i got not problems.
I too use UTF-8 in the complete database, so this should not be the problem.
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);
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");