Store Arabic text in mysql database using php [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I am trying to store some Arabic data in a mysql database
I have set the html document charset to be 'utf8'
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
MySQL charset is set to: UTF-8 Unicode (utf8)
MySQL connection collation is set to: utf8_general_ci
Database and table collations are set to: utf8_general_ci
In addition in my php code I used the $mysqli->set_charset("utf8") function to ensure that the charset is set to be ut8 but nothing is actually working , I am posting my data to the php script using html form where the enctype is : enctype="multipart/form-data" because in this form I also upload an image
The weird thing is that when I write my query directly in mysql the Arabic characters are stored properly with no problem , but when I use a php query to store the data all the characters are stored in a wrong charset encoding
Any suggestions ?

Weird, It should work!
Try adding these lines after a successful connection to the database:
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");
For example:
$mysqli = #new mysqli('DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME');
if($mysqli->connect_errno) die('Connection Error!');
else{
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");
}
And include these META tags in the head section of your php page:
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Browsers will ignore the <meta http-equiv ...> tag if there is a http header present. Try putting this at the top of your php page:
header("Content-Type: text/html; charset=UTF-8");

save this file in ur website, htdocs folder as "dbh.php, then in include it at the top of your index page by typing <?php include 'dbh.php';?> and you u are ready to go.
<?php
$conn = mysqli_connect("localhost", "root", "", "database name");
if(!$conn){
die("connection failed: ".mysqli_connect_error());
}else{
$conn->query("SET NAMES 'utf8'");
$conn->query("SET CHARACTER SET utf8");
}

You may try this. It should work
<?php
$conn = mysqli_connect(<host>, <user name>, <password>, <database name>);
if(!$conn){
die("could not connect: ".mysqli_connect_error());
}else{
mysqli_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);
}
?>

Related

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.

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.

sql data charset / charactter set , set names not working

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>

How to display Germany Umlauts (ü, ä, ö) from sql in 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);

MySQL database query coding problem in PHP

Hello I have this problem: I have MySQL Database with collation latin1_bin. In database I have table with collation utf8_slovak_ci. All collumns is text. In rows I have values with ť í ž ľ š č(utf8) chars, but PHP code returns values with utf8 chars replaced by � , ? and other not readable chars. In html head I have set charset to utf-8. Please help me. I have this code:
//From config file
define ("DATABASE_SERVER", "localhost");
define ("DATABASE_LOGIN", "root");
define ("DATABASE_PASSWORD", "root");
define ("DATABASE_DATABASE", "novymost");
mysql_connect(DATABASE_SERVER, DATABASE_LOGIN, DATABASE_PASSWORD)or die(mysql_error());
mysql_select_db("novymost")or die(mysql_error());
$results=mysql_query("SELECT * FROM Downloads") or die(mysql_error());
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
while($rows = mysql_fetch_array($results))
{
echo("<li>");
echo "<a href=\"".$rows["URL"];
echo("\">");
echo "".$rows["TITLE"];
echo(" - ".$rows["SIZE"]);
echo("</a>");
echo("<br/></li>");
}
run the query
mysql_query( "set names utf8" );
before runnign any other queries. This sets the connection charset
http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html
In php:
header("Content-Type: text/html; charset=UTF-8");
In HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
In Database before queries:
mysql_query( "set names utf8" );
Or you can also convert you latin-table to a UTF8-table:
INSERT INTO utf8table (utf8column)
SELECT CONVERT(latin1field USING utf8)
FROM latin1table;

Categories