MySQL database query coding problem in PHP - 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;

Related

How to get Arabic content from MSSQL server using ODBC connection?

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)

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)

I can't get Chinese characters from MYSQL to PHP

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');

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");

Categories